Rakesh Nittur
Rakesh Nittur

Reputation: 475

Adding a new key to the existing python dictionary

I have a dictionary:

oldDict = {'a': 'apple', 'b': 'boy', 'c': 'cat'}

I want a new dictionary with one of the values in the old dictionary as new key and all the elements as values:

newDict = {'apple': {'a': 'apple', 'b': 'boy', 'c': 'cat'}}

I tried doing this:

newDict['apple'] = oldDict

This does not seem to be working. Please note that I don't have a variable newDict in my script. I just have oldDict and I need to modify the same to make this change in every loop. In the end I will have one dictionary, which will look like this.

oldDict = {'apple': {'a': 'apple', 'b': 'boy', 'c': 'cat'}, 'dog': {'d': 'dog', 'e': 'egg'}}

Upvotes: 0

Views: 1042

Answers (2)

Skycc
Skycc

Reputation: 3555

you need to first create/declare the dictionary before you can added items into it

oldDict = {'a': 'apple', 'b': 'boy', 'c': 'cat'}
newDict = {}
newDict['apple'] = oldDict
# {'apple': {'a': 'apple', 'b': 'boy', 'c': 'cat'}}

# you can 1st create the newDict outside the loop then update it inside the loop
>>> newDict = {}
>>> dict1 = {'a': 'apple', 'b': 'boy', 'c': 'cat'}
>>> dict2 = {'d': 'dog', 'e': 'egg'}
>>> newDict['apple'] = dict1
>>> newDict['dog'] = dict2
>>> newDict
>>> {'apple': {'a': 'apple', 'b': 'boy', 'c': 'cat'}, 'dog': {'d': 'dog', 'e': 'egg'}}

or you could do as below

newDict = {'apple':oldDict}

Upvotes: 0

Josep Valls
Josep Valls

Reputation: 5560

You need to duplicate your dictionary so you won't create a circular reference.

>>> newDict = {'apple': {'a': 'apple', 'b': 'boy', 'c': 'cat'}}
>>> newDict['potato'] = dict(newDict)
>>> newDict
{'apple': {'a': 'apple', 'c': 'cat', 'b': 'boy'}, 'potato': {'apple': {'a': 'apple', 'c': 'cat', 'b': 'boy'}}}

Upvotes: 1

Related Questions