felix001
felix001

Reputation: 16691

Append a Dict to a Dict

I currently have a dictionary that looks like this :

{'BOB':  [['AUDI', 'BLACK', 'PETROL'],
          ['MINI', 'PINK', 'PETROL'],
          ['VW', 'BLUE', 'DIESEL']],
 'DAVE': [['BMW', 'PURPLE', 'PETROL'],
          ['VOLVO', 'GREY', 'PETROL']]}

What Im looking for is to add a dict to each keys list. The dict would be something like :

{'TYRE': RUBBER, 'ALLOY': 17, 'SUNROOF': YES} 

The end result would look like :

{'BOB':  [['AUDI', 'BLACK', 'PETROL',
           {'TYRE': RUBBER, 'ALLOY': 17, 'SUNROOF': YES}],
          ['MINI', 'PINK', 'PETROL',
           {'TYRE': RUBBER, 'ALLOY': 17, 'SUNROOF': YES}]
# ...

Thanks,

Upvotes: 0

Views: 308

Answers (2)

Ashwini Chaudhary
Ashwini Chaudhary

Reputation: 250951

dic={'BOB':  [['AUDI', 'BLACK', 'PETROL'],
          ['MINI', 'PINK', 'PETROL'],
          ['VW', 'BLUE', 'DIESEL']],
 'DAVE': [['BMW', 'PURPLE', 'PETROL'],
          ['VOLVO', 'GREY', 'PETROL']]}
dic1={'TYRE': 'RUBBER', 'ALLOY': 17, 'SUNROOF': 'YES'}
for x in dic:
    for y in dic[x]:
        y.append(dic1)
print dic    

output:

{'BOB': [['AUDI', 'BLACK', 'PETROL', {'ALLOY': 17, 'SUNROOF': 'YES', 'TYRE': 'RUBBER'}], ['MINI', 'PINK', 'PETROL', {'ALLOY': 17, 'SUNROOF': 'YES', 'TYRE': 'RUBBER'}], ['VW', 'BLUE', 'DIESEL', {'ALLOY': 17, 'SUNROOF': 'YES', 'TYRE': 'RUBBER'}]], 'DAVE': [['BMW', 'PURPLE', 'PETROL', {'ALLOY': 17, 'SUNROOF': 'YES', 'TYRE': 'RUBBER'}], ['VOLVO', 'GREY', 'PETROL', {'ALLOY': 17, 'SUNROOF': 'YES', 'TYRE': 'RUBBER'}]]}

Upvotes: 1

Martijn Pieters
Martijn Pieters

Reputation: 1121942

You are adding your additional dict to each list in the values, which are lists themselves. These are mutable, so just reference these inner lists directly:

for valuelist in yourdict.values():
    for sublist in valuelist:
        sublist.append(yourotherdict.copy())

Note the use of .copy() there; we are creating a new copy of the yourotherdict structure for appending each time, otherwise they will all be the same dict and manipulating one will manipulate all of the references in each list.

Upvotes: 2

Related Questions