在一行中连接字典数组

时间:2016-04-10 10:15:41

标签: python-3.x

如何将以下字典数组结构转换为只有一行refresh_token结构的字典?

'city': 'continent'

这段代码给了我答案:

info = [
    ({'Amsterdam':10,'Berlin':20,'London':30},'Europe'),
    ({'Hongkong':10,'Beijng':20,'Manila':30},'Asia'),
    ({'Nairobi':10,'Cape Town':20,'Cairo':30},'Africa')
]

这是不正确的:

a = dict()
for t in info:
    for i in t[0]:
        a[i]=t[1]

{'Amsterdam': 'Europe',
 'Beijng': 'Asia',
 'Berlin': 'Europe',
 'Cairo': 'Africa',
 'Cape Town': 'Africa',
 'Hongkong': 'Asia',
 'London': 'Europe',
 'Manila': 'Asia',
 'Nairobi': 'Africa'}

另一个连接字典数组的尝试也失败了:

a = {i:t[1] for i in t[0] for t in info}

1 个答案:

答案 0 :(得分:1)

试试这个(在3.5上测试):

a = {i: y for x, y in info for i in x}