user2990084
user2990084

Reputation: 2840

Create dictionary from list of tuples, wrong output

countries = [('AGO', 'ANGOLA'), ('PRT', 'PORTUGAL')]

countries_dict = {}
countries_new_list = []
for country_code, country in countries:
    print country_code
    countries_dict['country_code'] = country_code
    countries_new_list.append(countries_dict)

print countries_new_list

This code will print

AGO
PRT
[{'country_code': 'PRT'}, {'country_code': 'PRT'}]

And what i am expecting is:

AGO
PRT
[{'country_code': 'AGO'}, {'country_code': 'PRT'}]

What am I missing here?

http://codepad.org/nZblGER7

Upvotes: 1

Views: 61

Answers (3)

Vivek Sable
Vivek Sable

Reputation: 10223

Pythonic way by using list compression:-

>>> countries = [('AGO', 'ANGOLA'), ('PRT', 'PORTUGAL')]
>>> [{"country_code":i} for i ,j in countries]
[{'country_code': 'AGO'}, {'country_code': 'PRT'}]
>>> 

Upvotes: 4

Math
Math

Reputation: 2436

Your error comes from the fact that you append the dictionnary countries_dict in countries_new_list and not a copy.

You should either do countries_dict = {} in the for loop or use a copy:

from copy import copy
...
countries_new_list.append(copy(countries_dict))

Upvotes: 1

Avinash Raj
Avinash Raj

Reputation: 174706

I suggest you to define the dictionary countries_dict inside the for loop.

countries = [('AGO', 'ANGOLA'), ('PRT', 'PORTUGAL')]
countries_new_list = []
for country_code, country in countries:
    print country_code
    countries_dict = {}
    countries_dict['country_code'] = country_code
    countries_new_list.append(countries_dict)

print countries_new_list

Upvotes: 3

Related Questions