简体   繁体   中英

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:

[
  '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)

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? I want a result that looks this:

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

Using dict() and 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:

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 . 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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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