繁体   English   中英

使用Python中的词典列表创建新词典

[英]Creating a new dictionary from a list of dictionaries in Python

我有一个字典列表,其中一些值是字符串,而其他值是整数:

list_countries = [{'country' : 'Suriname', 
            'population' : 532724,
            'capital': 'Paramaribo', 
            'anthem': 'God zij met ons Suriname'},
            {'country' : 'Sweden', 
            'population' : 9683248,
            'capital': 'Stockholm', 
            'anthem': 'Du gamla, Du fria'},
             ...]

我想将每个键值对重塑为一个新的大词典。 但是,我的方法存在以下问题:

dict_countries = { 'countries':       [],
                   'pop':             [],
                   'capital_city':    [],
                   'national_anthem': [] }

然后,我遍历并使用.extend()附加所有值。

for dictionary in list_countries:
    dict_countries['countries'].extend(dictionary['country'])
    dict_countries['pop'].extend(dictionary['population'])
    dict_countries['capital_city'].extend(dictionary['capital'])
    dict_countries['national_anthem'].extend(dictionary['anthem'])

但是,这不起作用。 所有的字符串都一个字母一个字母地分解。 对于整数,我得到了错误:

TypeError: 'int' object is not iterable

这样做的正确方法是什么?

编辑:我相信每个键都有一个值。 但是,可以说没有。 如果找不到值,我将如何重写以上内容以添加NaN

.extend()期望传递给它的参数是可迭代的,即。 根据您的示例, population是一个整数,因此不可迭代,因此出现异常消息。

如果将其更改为.append() ,则其行为将与您期望的一样。

获得输出的原因是因为在列表上appendextend之间存在差异。 如果使用Iterable作为参数(字符串是) extend ,它将把Iterable的每个项目内联到dict(字符串的每个字母)中。 但是,它对于int来说是失败的,因为它不是可迭代的。 我宁愿用append其中就追加到在字典列表中。

list_countries = [{'country' : 'Suriname', 
            'population' : 532724,
            'capital': 'Paramaribo', 
            'anthem': 'God zij met ons Suriname'},
            {'country' : 'Sweden', 
            'population' : 9683248,
            'capital': 'Stockholm', 
            'anthem': 'Du gamla, Du fria'}]

dict_countries = { 'countries':       [],
                   'pop':             [],
                   'capital_city':    [],
                   'national_anthem': [] }

for dictionary in list_countries:
    dict_countries['countries'].append(dictionary['country'])
    dict_countries['pop'].append(dictionary['population'])
    dict_countries['capital_city'].append(dictionary['capital'])
    dict_countries['national_anthem'].append(dictionary['anthem'])

print dict_countries

您有两个问题需要解决:
从字典中构建值列表,然后将旧键转换为新名称。

使用内置词典的setdefault方法,并将翻译词典用作字面意义上的词典(即用于翻译)。

像这样设置翻译:

>>> translations = {'country': 'countries',
...                 'population': 'pop',
...                 'capital': 'capital_city',
...                 'anthem': 'national_anthem'}

然后建立您的新字典:

>>> merged = {}
>>> for d in list_countries:
...     for k in d:
...         key = translations.get(k, k)
...         merged.setdefault(key, []).append(d[k])
... 
>>> merged
{'national_anthem': ['God zij met ons Suriname', 'Du gamla, Du fria'], 'capital_city': ['Paramaribo', 'Stockholm'], 'pop': [532724, 9683248], 'countries': ['Suriname', 'Sweden']}

...并且如果您可以确定所有词典都共享相同的键,则这是一个单行代码:

>>> {translations.get(k,k):[d[k] for d in list_countries] for k in list_countries[0].keys()}
{'national_anthem': ['God zij met ons Suriname', 'Du gamla, Du fria'], 'capital_city': ['Paramaribo', 'Stockholm'], 'pop': [532724, 9683248], 'countries': ['Suriname', 'Sweden']}

这就是我所做的。 唯一的限制是新字典中的键不是语法上复数的,但是我想您可以在最后手动进行。

list_countries = [{'country' : 'Suriname', 
            'population' : 532724,
            'capital': 'Paramaribo', 
            'anthem': 'God zij met ons Suriname'},
            {'country' : 'Sweden', 
            'population' : 9683248,
            'capital': 'Stockholm', 
            'anthem': 'Du gamla, Du fria'},
             ]


from collections import defaultdict
d = defaultdict(list)
for i in list_countries:
   for k,v in i.items():
     d[k].append(v)

d可以轻松地转换为常规dict

keys =  list_countries[0].keys()
values = (list(t) for t in zip(*[d.values() for d in list_countries]))
dict(zip(keys, values))

暂无
暂无

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

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