0

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
]
Red
  • 26,798
  • 7
  • 36
  • 58
  • What is the fastest way between all the answers ? – TelegramCEO2 Jul 03 '20 at 13:07
  • I know that [unpacking is significantly faster than indexing](https://stackoverflow.com/q/13024416/13552470). – Red Jul 03 '20 at 13:10
  • @AnnZen Thanks! but, I want it like i said to be organized, so the first country should be the country with the largest population, and the rank should be 1 for this example. – TelegramCEO2 Jul 03 '20 at 13:21
  • @TelegramCEO2 That was not clear at all from the question. – alani Jul 03 '20 at 13:24
  • @TelegramCEO2 I have added "update" section to my answer, which I believe now captures your requirements, but some example output in the question would have helped to communicate what you meant. – alani Jul 03 '20 at 13:32

4 Answers4

2

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, e.g.:

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'}]
alani
  • 12,573
  • 2
  • 13
  • 23
  • @AnnZen Commas? You mean as in `'1,000'`? There is no such requirement stated. – alani Jul 03 '20 at 13:54
  • @AnnZen It is, Sorry but your code still does not organize correctly by Population, country and rank. – TelegramCEO2 Jul 03 '20 at 13:55
  • @alaniwi Stated in the comments. – Red Jul 03 '20 at 13:55
  • @alaniwi With your code it works good with commas, *10,824" for example. – TelegramCEO2 Jul 03 '20 at 13:55
  • @alaniwi Mine works, but i pasted the wrong output :( – Red Jul 03 '20 at 13:57
  • @TelegramCEO2 No, I have not done anything to support commas. The only reference to commas that I could find was in a comment under AnnZen's answer. Please state all requirements in the question itself, as people will answer your question as stated. – alani Jul 03 '20 at 13:59
  • @alaniwi Yeah sorry, I just added `self.result_list_of_dicts.sort(key=lambda d: -int(d['Population'].replace(',', '')))` and it supported commas. – TelegramCEO2 Jul 03 '20 at 14:01
1

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'}]
Red
  • 26,798
  • 7
  • 36
  • 58
  • When I add a comma to one of the populations I get an error: ValueError: invalid literal for int() with base 10: '1,400', can you handle this please ? Thanks. – TelegramCEO2 Jul 03 '20 at 13:44
  • @TelegramCEO2 I updated to make the program support commas. – Red Jul 03 '20 at 13:46
0

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]})
Gamopo
  • 1,600
  • 1
  • 14
  • 22
0

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)
Jan
  • 42,290
  • 8
  • 54
  • 79