简体   繁体   English

将元组转换为字典

[英]Convert a tuple into a dictionary

I've looked all over the internet and consulted a few books but I can't seem to find an example that illustrates what I am trying to do. 我看过整个互联网,并查阅了几本书,但我似乎无法找到一个例子来说明我想要做的事情。 I loathe to ask this on SO because it feels like a really basic question but I've been banging my head against the wall for the last few hours so here it goes: 我不喜欢问这个问题,因为这感觉就像一个非常基本的问题,但是过去几个小时我一直在撞墙,所以在这里:

How do i turn this: 我怎么转这个:

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

into this: 进入这个:

                {
                item:[
                    {
                        value:100,
                        label:'May'
                    },
                    {
                        value:160,
                        label:'June'
                    },
                    {
                        value:300,
                        label:'July'
                    },
                    {
                        value:140,
                        label:'August'
                    }
                ]
                }
{'item': [dict(value=value, label=label) for value, label in item]}
>>> 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}]}
dict(item=map(lambda x: dict(value=x[0],label=x[1]),item))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM