Reputation: 1
Iam trying to create a list of dictionaries, but seems to me, that i am doing something wrong:
So, I have a list of tuples, something like this:
dict = {}
lst = []
cats = [(u'cat1', u'Matilda'),(u'cat2', u'Mew')]
for line in cats:
dict['cat_num'] = line[0]
dict['name'] = line[1]
lst.append(dict)
print lst
As a result I am getting this list:
[{'cat_num': u'cat2', 'name': u'Mew'}, {'cat_num': u'cat2', 'name': u'Mew'}]
Can anyone tell me where is my mistake?
Thank you.
Upvotes: 0
Views: 312
Reputation: 9176
Remember that dict()
is actually a builtin Python function that builds dictionaries, so it is probably not a good idea to rename it. Why not do something like,
cats = [(u'cat1', u'Matilda'),(u'cat2', u'Mew')]
lst = [dict(cat_num=c,name=n) for c,n in cats]
Upvotes: 4
Reputation: 159915
Since dict
has already been created you are appending a reference
to the dictionary to the array (lst
) and altering it for every line in cats
.
To see this, simply print
your dictionary for each iteration:
tmp = {}
final_results = []
cats = [(u'cat1', u'Matilda'),(u'cat2', u'Mew')]
for line in cats:
tmp['cat_num'] = line[0]
tmp['name'] = line[1]
print "For", line, "the dictionary is", tmp
final_results.append(dict)
print "The final list is:", final_results
All you need to do is create a new dictionary each time, and your problems will be solved:
final_results = []
cats = [(u'cat1', u'Matilda'),(u'cat2', u'Mew')]
for line in cats:
final_results.append( \
{'cat_num': line[0],
'name': line[1]} \
)
SEE ALSO: "Least Astonishment" and the Mutable Default Argument for other places where this behavior might surprise you.
Upvotes: 0
Reputation: 601779
Move the definition of dct
inside the loop (and don't call it dict
, since this is the name of the class):
lst = []
cats = [(u'cat1', u'Matilda'),(u'cat2', u'Mew')]
for line in cats:
dct = {}
dct['cat_num'] = line[0]
dct['name'] = line[1]
lst.append(dct)
print lst
Upvotes: 5
Reputation: 42188
First you need to create a dictionary for every tuple. Before you were using only one, shared dictionary:
lst = []
cats = [(u'cat1', u'Matilda'),(u'cat2', u'Mew')]
for line in cats:
d = {}
d['cat_num'] = line[0]
d['name'] = line[1]
lst.append(d)
print lst
Upvotes: 1