suneet
suneet

Reputation: 400

Undesired behaviour on iterating with list of dictionary in python

So I have this results variable containing list of objects. So i write this code

entry = {}
temp = []
temp2 = []
for result in results:
    entry['value'] = result['fb_id']
    entry['label'] = result['full_name']

    temp.append(entry)
    temp2.append(result)

    print (result)
    print (entry)

print temp
print temp2

This prints

{'fb_id': 17500787L, 'full_name': u'Sandipan Mondal'}  #this is result1
{'value': 17500787L, 'label': u'Sandipan Mondal'}      #this is entry1
{'fb_id': 597333664L, 'full_name': u'Aakash Tulsani'}  #this is result2
{'value': 597333664L, 'label': u'Aakash Tulsani'}      #this is entry2

[{'value': 597333664L, 'label': u'Aakash Tulsani'},       #this is temp
{'value': 597333664L, 'label': u'Aakash Tulsani'}]

[{'fb_id': 17500787L, 'full_name': u'Sandipan Mondal'},   #this is temp2
{'fb_id': 597333664L, 'full_name': u'Aakash Tulsani'}

Now temp2 variable comes out to be as expected i.e. [result1, result2] but that's not happening with temp variable. It is repeating entry2

Upvotes: 0

Views: 57

Answers (1)

msvalkon
msvalkon

Reputation: 12077

That's because you're overwriting the contents of entry at every iteration. This means that you keep a list of references in the list temp to the same dictionary entry and keep appending this dictionary over and over again. Reset the dictionary at each iteration:

for result in results:
    entry = {}

    entry['value'] = result['fb_id']
    entry['label'] = result['full_name']

    temp.append(entry)
    temp2.append(result)

    print (result)
    print (entry)

You don't need the temp2 at all, as you already have your results in the results list you're iterating. So just use that. As for the converted entries, if you hold a key mapping for the conversion, you can do something like this:

>>> m = {'fb_id': 'value', 'full_name': 'label'}
>>> [{m[k]: v for k, v in result.iteritems()} for result in results]
[{'label': u'Sandipan Mondal', 'value': 17500787L},
 {'label': u'Aakash Tulsani', 'value': 597333664L}]

This uses a list and dictionary comprehension to iterate over each dictionary in results and gets the correct key for each key and value-pair from the conversion dictionary m.

Upvotes: 5

Related Questions