-1

I want list d = [{'name': 'Ada Lovelace'},{'name': 'Alan Turing'}].

But the dictionary mutates

    >>> a = ['Ada Lovelace','Alan Turing']
    >>> c = dict()
    >>> d = []
    >>> for i in a:
    ...    print c
    ...    print d
    ...    c['name'] = i
    ...    d.append(c)
    ...    print c
    ...    print d
    ... 
    {}
    []
    {'name': 'Ada Lovelace'}
    [{'name': 'Ada Lovelace'}]
    {'name': 'Ada Lovelace'}
    [{'name': 'Ada Lovelace'}]
    {'name': 'Alan Turing'}
    [{'name': 'Alan Turing'}, {'name': 'Alan Turing'}]
Ashwini Chaudhary
  • 232,417
  • 55
  • 437
  • 487
Praveen Singh Yadav
  • 1,743
  • 4
  • 19
  • 30

2 Answers2

3

You are reusing the same dictionary over and over again. Create a new dictionary in the loop instead:

for i in a:
    c = {'name': i}
    d.append(c)

Appending an object to a list does not create a copy; it merely stores a reference to that object in the list.

By re-using the same dict object over and over again, you are merely appending multiple references to one dictionary to the list.

Martijn Pieters
  • 963,270
  • 265
  • 3,804
  • 3,187
0

Using the dictionary literal syntax, along with a list comprehension will do what you need:

>>> names = ['foo','bar']
>>> d = [{'name': i} for i in names]
>>> d
[{'name': 'foo'}, {'name': 'bar'}]
Burhan Khalid
  • 161,711
  • 18
  • 231
  • 272