简体   繁体   中英

Create a list of many dicts

I want to get 3 lists of information about countries, and then add one by one to a new dict in a list, I want it to by organize and clean, so the population and ranks. So the first country should be the country with the largest population, and the rank should be 1 for this example.

I have 3 lists for 3 countries:

countries = ['Argentina', 'Brazil', 'France']
population = ['100', '900', '1400']
ranks = ['1', '2', '3']

result_list_of_dicts = [
    {
        'Country': 'COUNTRY',
        'Rank': 'RANK',
        'Population': 'POPULATION'
    }
    {
        'Country': 'COUNTRY',
        'Rank': 'RANK',
        'Population': 'POPULATION'
    }
    # etc
]

Use zip inside a list comprehension. This gives a sequence of tuples, which you can then either index or unpack to create the values in the dictionary. The following example uses unpacking:

countries = ['Argentina', 'Brazil', 'France']
population = ['100', '900', '1400']
ranks = ['1', '2', '3']

result_list_of_dicts = [
    {'Country': country,
     'Rank': rank,
     'Population': pop}
    for country, rank, pop in zip(countries, ranks, population)]

If you prefer to use indexing rather than unpacking, then it would look like:

result_list_of_dicts = [
    {'Country': t[0],
     'Rank': t[1],
     'Population': t[2]}
    for t in zip(countries, ranks, population)]

where t contains a 3-element tuple.

The list comprehension is only a convenience, and in both of the above cases, you could instead use an explicit loop in which you append a single dictionary to a list, eg:

result_list_of_dicts = []
for country, rank, pop in zip(countries, ranks, population):
    result_list_of_dicts.append({'Country': country,
                                 'Rank': rank,
                                 'Population': pop})


Update:

Based on subsequent comment from TelegramCEO2, the requirement is to sort the dictionaries in order of increasing population, and the rank should relate to this sort order (in which case the purpose of the input list of ranks is unclear). Omitting 'Rank' and then adding appropriate post-processing in which the list is sorted and 'Rank' items added to the dictionaries, the following can be obtained:

countries = ['Argentina', 'Brazil', 'France']
population = ['100', '900', '1400']

result_list_of_dicts = [
    {'Country': country,
     'Population': pop}
    for country, pop in zip(countries, population)]

result_list_of_dicts.sort(key=lambda d:-int(d['Population']))

for (i, d) in enumerate(result_list_of_dicts):
    d['Rank'] = str(1 + i)
        
print(result_list_of_dicts)

which gives:

[{'Country': 'France', 'Population': '1400', 'Rank': '1'}, {'Country': 'Brazil', 'Population': '900', 'Rank': '2'}, {'Country': 'Argentina', 'Population': '100', 'Rank': '3'}]

Here is how you can use zip() :

countries = ['Argentina', 'Brazil', 'France']
population = ['100', '900', '1400']
ranks = ['1', '2', '3']

result_list_of_dicts = [{'country': c,
                         'rank': r,
                         'populations': p}
                        for c, p, r in
                        zip(countries, population, ranks)]

print(result_list_of_dicts)

Output:

[{'country': 'Argentina', 'rank': '1', 'populations': '100'},
 {'country': 'Brazil', 'rank': '2', 'populations': '900'},
 {'country': 'France', 'rank': '3', 'populations': '1400'}]

UPDATE:

Turns out the populations should be sorted so that the greatest population goes to the first country in the list, and the smallest population goes to the last country in the list, and the ranks are ranked by the number of population of each country:

countries = ['Argentina', 'Brazil', 'France']
population = ['100', '900', '1400']
ranks = ['1', '2', '3']


population = sorted(population,reverse=True,key=lambda x:int(x.replace(',','')))
ranks = sorted(ranks,key=lambda x:int(x))

result_list_of_dicts = [{'country': c,
                         'rank': r,
                         'populations': p}
                        for c, p, r in
                        zip(countries,
                            population,
                            ranks)]

print(result_list_of_dicts)

Output:

[{'country': 'Argentina', 'rank': '1', 'populations': '1400'},
 {'country': 'Brazil', 'rank': '2', 'populations': '900'},
 {'country': 'France', 'rank': '3', 'populations': '100'}]


The ranks list can be left out altogether now that we know the ranks are consistent:

countries = ['Argentina', 'Brazil', 'France']
population = ['100', '900', '1400']

population = sorted(population,reverse=True,key=lambda x:int(x.replace(',','')))

result_list_of_dicts = [{'country': c,
                         'rank': r,
                         'populations': p}
                        for r, (c, p) in
                        enumerate(zip(countries,
                                      population), 1)]

print(result_list_of_dicts)

Output:

[{'country': 'Argentina', 'rank': 1, 'populations': '1400'},
 {'country': 'Brazil', 'rank': 2, 'populations': '900'},
 {'country': 'France', 'rank': 3, 'populations': '100'}]

This code should do the job:

result_list_of_dicts = []
for i in range(len(countries)):
    result_list_of_dicts.append({'country': countries[i], 'rank': ranks[i],  'population': population[i]})

Use zip in combination with a comprehension:

countries = ['Argentina', 'Brazil', 'France']
population = ['100', '900', '1400']
ranks = ['1', '2', '3']

result_list_of_dicts = [{"Country": country, "Rank": rank, "Population": pop}
                        for country, rank, pop in zip(countries, ranks, population)]
print(result_list_of_dicts)

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