Convert a tuple to a dictionary

I have looked all over the internet and consulted with several books, but I cannot find an example illustrating what I am trying to do. I hate asking about it on SO because it seems like a really basic question, but I hit my head on the wall in the last few hours, so here it is:

How to do it:

   item = ((100,May),(160,June),(300,July),(140,August))  

in it:

                {
                item:[
                    {
                        value:100,
                        label:'May'
                    },
                    {
                        value:160,
                        label:'June'
                    },
                    {
                        value:300,
                        label:'July'
                    },
                    {
                        value:140,
                        label:'August'
                    }
                ]
                }
+3
source share
3 answers
{'item': [dict(value=value, label=label) for value, label in item]}
+9
source
>>> item = ((100,'May'),(160,'June'),(300,'July'),(140,'August'))
>>> keys = ('value','label')
>>> dd = {'item' : [dict(zip(keys,pair)) for pair in item]}
>>>
>>> import pprint
>>> pprint.pprint(dd)
{'item': [{'label': 'May', 'value': 100},
          {'label': 'June', 'value': 160},
          {'label': 'July', 'value': 300},
          {'label': 'August', 'value': 140}]}
+1
source
dict(item=map(lambda x: dict(value=x[0],label=x[1]),item))
0
source

Source: https://habr.com/ru/post/1794381/


All Articles