Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/342.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
从Python中的词典列表创建新词典_Python_Dictionary - Fatal编程技术网

从Python中的词典列表创建新词典

从Python中的词典列表创建新词典,python,dictionary,Python,Dictionary,我有一个字典列表,其中一些值是字符串,其他值是整数: list_countries = [{'country' : 'Suriname', 'population' : 532724, 'capital': 'Paramaribo', 'anthem': 'God zij met ons Suriname'}, {'country' : 'Sweden', 'popula

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

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()
遍历并附加所有值

然而,这不起作用。所有的线都被一个字母一个字母地断开了。对于整数,我得到一个错误:

TypeError: 'int' object is not iterable
正确的方法是什么


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

以下是我所做的。唯一的限制是新字典中的键在语法上没有多元化,但我想你可以在最后手动完成

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

以下是我所做的。唯一的限制是新字典中的键在语法上没有多元化,但我想你可以在最后手动完成

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

.extend()
希望传递给它的参数是一个可iterable,即列表或字符串等。根据您的示例,
population
是一个整数,因此不可iterable,因此出现异常消息

如果将其更改为
.append()
,它将按照您的预期运行。

.extend()
希望传递给它的参数是一个iterable,即列表或字符串等。根据您的示例,
population
是一个整数,因此不可iterable,因此会显示异常消息


如果您将其更改为
.append()
,它将按照您的预期运行。

您获得输出的原因是列表上的
append
extend
之间存在差异。如果使用iterable作为参数(字符串是)扩展
,它会将iterable的每个项目内联到dict(字符串的每个字母)中。但是,它对int失败,因为它不是一个iterable。我更喜欢使用
append
,它只是简单地附加到dict中的列表中

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

您获得当前输出的原因是列表上的
append
extend
之间存在差异。如果使用iterable作为参数(字符串是)扩展
,它会将iterable的每个项目内联到dict(字符串的每个字母)中。但是,它对int失败,因为它不是一个iterable。我更喜欢使用
append
,它只是简单地附加到dict中的列表中

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']}

这里有两个问题需要解决:
从字典中建立值的列表,并将旧键转换为它们的新名称

使用内置字典的
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']}

考虑一下你是否真的想这么做。你的列表有点脆弱:如果任何一个列表不同步,整个事情就会变得一团糟。另一种方法是按国家索引的dict of dict。@PM2Ring我将在一个数据框中导入此词典。也许我会再次问这个问题是怎么做的。考虑一下你是否真的想这么做。你的列表有点脆弱:如果任何一个列表不同步,整个事情就会变得一团糟。另一种方法是按国家索引的dict of dict。@PM2Ring我将在一个数据框中导入此词典。也许我会重新问这个问题,看看如何做到这一点。您可以使用
collections.defaultdict
来避免
setdefault
(我发现它更干净了一点)。否则,这是一个不错的方法+1您可以使用
collections.defaultdict
来避免
setdefault
(我发现它有点干净)。否则,这是一个不错的方法+1您无法保证字典将返回具有相同模式的值。是的,这是典型实现的情况,但这不是dict的保证。因此,您的方法可能会产生类似于
'country':['Suriname',12345',France','Berlin']
Python文档状态:If items()、key()、values()、iteritems()、iterkeys()和itervalues()如果调用时没有对词典进行任何修改,则列表将直接对应。这允许使用zip()创建(值、键)对:pairs=zip(d.values(),d.keys())。是的。同一本词典。您正在将其用于几本词典。据我所知,没有任何保证。(我已经考虑到了这一点,我的示例中的第一个国家确实是出于这个原因的国家,这不是巧合)您无法保证字典将返回具有相同模式的值。是的,这是典型实现的情况,但这不是dict的保证。因此,您的方法可能会产生类似于
'country':['Suriname',12345',France','Berlin']
Python文档状态:If items()、key()、values()、iteritems()、iterkeys()和itervalues()调用时不需要对字典进行任何修改