-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
  • 244,495
  • 58
  • 464
  • 504
Praveen Singh Yadav
  • 1,831
  • 4
  • 20
  • 31

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
  • 1,048,767
  • 296
  • 4,058
  • 3,343
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
  • 169,990
  • 18
  • 245
  • 284