简体   繁体   English

如何将具有多个值的列表转换成只有2个值的字典?

[英]How do i turn a list with multiple values into a dictionary with only 2 values?

I have a list called country_population, looking like this: 我有一个名为country_population的列表,看起来像这样:

[
  'Guam',
  {'total_population': {'date': '2013-01-01', 'population': 163943}},
  'Central%20African%20Republic',
  {'total_population': {'date': '2013-01-01', 'population': 4665025}}
]

I've tried to do dict(country_population) 我试着做dict(country_population)

which gives me the following error: 这给了我以下错误:

ValueError: dictionary update sequence element #0 has length 4; 2 is required

I understand that my list has 4 values, but how do i turn it into a dictionary with only 2 values? 我了解我的清单有4个值,但是如何将它变成只有2个值的字典? I want a result that looks this: 我想要一个看起来像这样的结果:

country_population = {'Guam' : '163943, 'Central%20African%20Republic' : 
'4665025' } 

Using dict() and zip 使用dict()zip

Demo: 演示:

country_population = ['Guam', {'total_population': {'date': '2013-01-01', 'population': 163943}}, 'Central%20African%20Republic', {'total_population': {'date': '2013-01-01', 'population': 4665025}}]
print(dict((i[0], i[1]['total_population']["population"])for i in zip(country_population[0::2], country_population[1::2])))

Output: 输出:

{'Central%20African%20Republic': 4665025, 'Guam': 163943}

You can try: 你可以试试:

my_list = ['Guam', {'total_population': {'date': '2013-01-01', 'population': 163943}}, 'Central%20African%20Republic', {'total_population': {'date': '2013-01-01', 'population': 4665025}}]
# dictionary to store new results
result = {}

for i in range(0, len(my_list), 2):
    result[my_list[i]] = my_list[i+1]['total_population']['population']

print(result)

Result: 结果:

{'Central%20African%20Republic': 4665025, 'Guam': 163943}

And for above code using dictionary comprehension , you can try as: 对于上面使用dictionary comprehension代码,您可以尝试:

result = {my_list[i] : my_list[i+1]['total_population']['population'] 
                                                for i in range(0, len(my_list), 2)}

The result that you described is invalid because it has multiple keys called Name and Population . 您描述的结果无效,因为它具有多个名为NamePopulation键。 I think what you want is Name to be the key and Population to be the value, which you can do by jumping through the list in increments of two and adding each pair to a dict. 我认为您想要的是“ Name作为关键字,“ Population作为值,您可以通过以两个为增量跳过列表并将每对加到字典中来实现。

d=dict()
for i in range(len(country_population)/2):
    d[country_population[2*i]] = 
        country_population[2*i+1]['total_population']['population']

The result of d['Guam'] will be 163943. d['Guam']将是163943。

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

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