Adding a new key to the existing python dictionary - python

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'}}

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'}}}

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}

Related

Swap keys of nested dictionaries

I have a dictionary as follows:
Each key has a dictionary associated with it.
dict_sample = {'a': {'d0': '1', 'd1': '2', 'd2': '3'}, 'b': {'d0': '1'}, 'c': {'d1': '1'}}
I need the output as follows:
output_dict = {'d0': {'a': 1, 'b': 1}, 'd1': {'a': 2, 'c': 1}, 'd2': {'a': 3}}
I'd appreciate any help on the pythonic way to achieve this. Thank You !
I believe this produces the desired output
>>> from collections import defaultdict
>>> d = defaultdict(dict)
>>>
>>> dict_sample = {'a': {'d0': '1', 'd1': '2', 'd2': '3'}, 'b': {'d0': '1'}, 'c': {'d1': '1'}}
>>>
>>> for key, value in dict_sample.items():
... for k, v in value.items():
... d[k][key] = v
...
>>> d
defaultdict(<class 'dict'>, {'d0': {'a': '1', 'b': '1'}, 'd1': {'a': '2', 'c': '1'}, 'd2': {'a': '3'}})
You can use dict.setdefault on a new dict with a nested loop:
d = {}
# for each key and sub-dict in the main dict
for k1, s in dict_sample.items():
# for each key and value in the sub-dict
for k2, v in s.items():
# this is equivalent to d[k2][k1] = int(v), except that when k2 is not yet in d,
# setdefault will initialize d[k2] with {} (a new dict)
d.setdefault(k2, {})[k1] = int(v)
d would become:
{'d0': {'a': 1, 'b': 1}, 'd1': {'a': 2, 'c': 1}, 'd2': {'a': 3}}

How to convert list of dictionaries to dictionaries

mylist = [{'a': 1, 'b': 2}, {'c': 3, 'd': 4}, {'e': 5, 'f': 6}]
i want it as
myDict ={'a': 1, 'b': 2,'c': 3, 'd': 4,'e': 5, 'f': 6}
You can make use of ChainMap.
from collections import ChainMap
myDict = dict(ChainMap(*mylist ))
This will take each dictionary and iterate through its key value pairs in for (k,v) in elem.items() part and assign them to a new dictionary.
mylist = [{'a': 1, 'b': 2}, {'c': 3, 'd': 4}, {'e': 5, 'f': 6}]
new_dict = {k:v for elem in mylist for (k,v) in elem.items()}
print new_dict
This will replace the duplicated keys.
I would create a new dictionary, iterate over the dictionaries in mylist, then iterate over the key/value pairs in that dictionary. From there, you can add each key/value pair to myDict.
mylist = [{'a': 1, 'b': 2}, {'c': 3, 'd': 4}, {'e': 5, 'f': 6}]
myDict = {}
for Dict in mylist:
for key in Dict:
myDict[key] = Dict[key]
print(myDict)

Python - Flatten the list of dictionaries

List of dictionaries:
data = [{
'a':{'l':'Apple',
'b':'Milk',
'd':'Meatball'},
'b':{'favourite':'coke',
'dislike':'juice'}
},
{
'a':{'l':'Apple1',
'b':'Milk1',
'd':'Meatball2'},
'b':{'favourite':'coke2',
'dislike':'juice3'}
}, ...
]
I need to join all nested dictionaries to reach at the expected output:
[{'d': 'Meatball', 'b': 'Milk', 'l': 'Apple', 'dislike': 'juice', 'favourite': 'coke'},
{'d': 'Meatball2', 'b': 'Milk1', 'l': 'Apple1', 'dislike': 'juice3', 'favourite': 'coke2'}]
I try nested list comprehension, but cannot join dict together:
L = [y for x in data for y in x.values()]
print (L)
[{'d': 'Meatball', 'b': 'Milk', 'l': 'Apple'},
{'dislike': 'juice', 'favourite': 'coke'},
{'d': 'Meatball2', 'b': 'Milk1', 'l': 'Apple1'},
{'dislike': 'juice3', 'favourite': 'coke2'}]
I am looking for the fastest solution.
You can do the following, using itertools.chain:
>>> from itertools import chain
# timeit: ~3.40
>>> [dict(chain(*map(dict.items, d.values()))) for d in data]
[{'l': 'Apple',
'b': 'Milk',
'd': 'Meatball',
'favourite': 'coke',
'dislike': 'juice'},
{'l': 'Apple1',
'b': 'Milk1',
'dislike': 'juice3',
'favourite': 'coke2',
'd': 'Meatball2'}]
The usage of chain, map, * make this expression a shorthand for the following doubly nested comprehension which actually performs better on my system (Python 3.5.2) and isn't that much longer:
# timeit: ~2.04
[{k: v for x in d.values() for k, v in x.items()} for d in data]
# Or, not using items, but lookup by key
# timeit: ~1.67
[{k: x[k] for x in d.values() for k in x} for d in data]
Note:
RoadRunner's loop-and-update approach outperforms both these one-liners at timeit: ~1.37
You can do this with 2 nested loops, and dict.update() to add inner dictionaries to a temporary dictionary and add it at the end:
L = []
for d in data:
temp = {}
for key in d:
temp.update(d[key])
L.append(temp)
# timeit ~1.4
print(L)
Which Outputs:
[{'l': 'Apple', 'b': 'Milk', 'd': 'Meatball', 'favourite': 'coke', 'dislike': 'juice'}, {'l': 'Apple1', 'b': 'Milk1', 'd': 'Meatball2', 'favourite': 'coke2', 'dislike': 'juice3'}]
You can use functools.reduce along with a simple list comprehension to flatten out the list the of dicts
>>> from functools import reduce
>>> data = [{'b': {'dislike': 'juice', 'favourite': 'coke'}, 'a': {'l': 'Apple', 'b': 'Milk', 'd': 'Meatball'}}, {'b': {'dislike': 'juice3', 'favourite': 'coke2'}, 'a': {'l': 'Apple1', 'b': 'Milk1', 'd': 'Meatball2'}}]
>>> [reduce(lambda x,y: {**x,**y},d.values()) for d in data]
>>> [{'dislike': 'juice', 'l': 'Apple', 'd': 'Meatball', 'b': 'Milk', 'favourite': 'coke'}, {'dislike': 'juice3', 'l': 'Apple1', 'd': 'Meatball2', 'b': 'Milk1', 'favourite': 'coke2'}]
Time benchmark is as follows:
>>> import timeit
>>> setup = """
from functools import reduce
data = [{'b': {'dislike': 'juice', 'favourite': 'coke'}, 'a': {'l': 'Apple', 'b': 'Milk', 'd': 'Meatball'}}, {'b': {'dislike': 'juice3', 'favourite': 'coke2'}, 'a': {'l': 'Apple1', 'b': 'Milk1', 'd': 'Meatball2'}}]
"""
>>> min(timeit.Timer("[reduce(lambda x,y: {**x,**y},d.values()) for d in data]",setup=setup).repeat(3,1000000))
>>> 1.525032774952706
Time benchmark of other answers on my machine
>>> setup = """
data = [{'b': {'dislike': 'juice', 'favourite': 'coke'}, 'a': {'l': 'Apple', 'b': 'Milk', 'd': 'Meatball'}}, {'b': {'dislike': 'juice3', 'favourite': 'coke2'}, 'a': {'l': 'Apple1', 'b': 'Milk1', 'd': 'Meatball2'}}]
"""
>>> min(timeit.Timer("[{k: v for x in d.values() for k, v in x.items()} for d in data]",setup=setup).repeat(3,1000000))
>>> 2.2488374650129117
>>> min(timeit.Timer("[{k: x[k] for x in d.values() for k in x} for d in data]",setup=setup).repeat(3,1000000))
>>> 1.8990078769857064
>>> code = """
L = []
for d in data:
temp = {}
for key in d:
temp.update(d[key])
L.append(temp)
"""
>>> min(timeit.Timer(code,setup=setup).repeat(3,1000000))
>>> 1.4258553800173104
>>> setup = """
from itertools import chain
data = [{'b': {'dislike': 'juice', 'favourite': 'coke'}, 'a': {'l': 'Apple', 'b': 'Milk', 'd': 'Meatball'}}, {'b': {'dislike': 'juice3', 'favourite': 'coke2'}, 'a': {'l': 'Apple1', 'b': 'Milk1', 'd': 'Meatball2'}}]
"""
>>> min(timeit.Timer("[dict(chain(*map(dict.items, d.values()))) for d in data]",setup=setup).repeat(3,1000000))
>>> 3.774383604992181
If you have nested dictionaries with only 'a' and 'b' keys, then I suggest the following solution I find fast and very easy to understand (for readability purpose):
L = [x['a'] for x in data]
b = [x['b'] for x in data]
for i in range(len(L)):
L[i].update(b[i])
# timeit ~1.4
print(L)

Get dictionary contains in list if key and value exists

How to get complete dictionary data inside lists. but first I need to check them if key and value is exists and paired.
test = [{'a': 'hello' , 'b': 'world', 'c': 1},
{'a': 'crawler', 'b': 'space', 'c': 5},
{'a': 'jhon' , 'b': 'doe' , 'c': 8}]
when I try to make it conditional like this
if any((d['c'] is 8) for d in test):
the value is True or False, But I want the result be an dictionary like
{'a': 'jhon', 'b': 'doe', 'c': 8}
same as if I do
if any((d['a'] is 'crawler') for d in test):
the results is:
{'a': 'crawler', 'b': 'space', 'c': 5}
Thanks in advance
is tests for identity, not for equality which means it compares the memory address not the values those variables are storing. So it is very likely it might return False for same values. You should use == instead to check for equality.
As for your question, you can use filter or list comprehensions over any:
>>> [dct for dct in data if dct["a"] == "crawler"]
>>> filter(lambda dct: dct["a"] == "crawler", data)
The result is a list containing the matched dictionaries. You can get the [0]th element if you think it contains only one item.
Use comprehension:
data = [{'a': 'hello' , 'b': 'world', 'c': 1},
{'a': 'crawler', 'b': 'space', 'c': 5},
{'a': 'jhon' , 'b': 'doe' , 'c': 8}]
print([d for d in data if d["c"] == 8])
# [{'c': 8, 'a': 'jhon', 'b': 'doe'}]

While Dynamically creating dictionaries with a reference dictionary, why is the reference dictionaries getting modified? (Python)

I was writing a Python Code that creates dictionaries dynamically,initializes it to a reference dictionary, and modifying a particular value in the dictionary. But,I found that not only I am getting unexpected results,but the reference dictionary is also getting modified.
My Code:
tdict={'a':'1','b':'2','c':'3'}
newdict={}
for i in range(5):
newdict['name'+str(i)]=tdict
newdict['name'+str(i)]['a']='value'+str(i)
print 'tdict: ',tdict
print 'newdict: ',newdict
And the result:
tdict: {'a': 'value0', 'c': '3', 'b': '2'}
tdict: {'a': 'value1', 'c': '3', 'b': '2'}
tdict: {'a': 'value2', 'c': '3', 'b': '2'}
tdict: {'a': 'value3', 'c': '3', 'b': '2'}
tdict: {'a': 'value4', 'c': '3', 'b': '2'}
newdict: {'name4': {'a': 'value4', 'c': '3', 'b': '2'}, 'name2': {'a': 'value4', 'c': '3', 'b': '2'}, 'name3': {'a': 'value4', 'c': '3', 'b': '2'}, 'name0': {'a': 'value4', 'c': '3', 'b': '2'}, 'name1': {'a': 'value4', 'c': '3', 'b': '2'}}
whereas I expected my 'newdict' to be like:
newdict: {'name4': {'a': 'value4', 'c': '3', 'b': '2'}, 'name2': {'a': 'value2', 'c': '3', 'b': '2'}, 'name3': {'a': 'value3', 'c': '3', 'b': '2'}, 'name0': {'a': 'value0', 'c': '3', 'b': '2'}, 'name1': {'a': 'value1', 'c': '3', 'b': '2'}}
Can anyone please help me figuring out why this is happening? Also, why is the reference dictionary 'tdict' getting changed when I am not assigning any any value to it?
Thanks in advance
You are storing a reference to tdict in every value of your newdict dictionary:
newdict['name'+str(i)]=tdict
You are then modifying the key 'a' of tdict by doing
# newdict['name'+str(i)] is a reference to tdict
newdict['name'+str(i)]['a']='value'+str(i)
# this is equivalent to doing
tdict['a']='value'+str(i)
What you maybe want is storing a copy of tdict in your newdict dictionary:
newdict['name'+str(i)]=dict(tdict)
Creating a new dictionary by using an existing dictionary as constructor argument creates a shallow copy where you can assign new values to existing keys. What you cannot (or what you don't want) is modifying mutable values in this dictionary. Example:
>>> a={'a': 1, 'b': 2, 'c': [1,2,3]}
>>> b=dict(a)
>>> b['a']=9
>>> a
{'a': 1, 'c': [1, 2, 3], 'b': 2}
>>> b
{'a': 9, 'c': [1, 2, 3], 'b': 2}
>>> b['c'].append(99)
>>> a
{'a': 1, 'c': [1, 2, 3, 99], 'b': 2}
>>> b
{'a': 9, 'c': [1, 2, 3, 99], 'b': 2}
If you want to modify mutable values in a dictionary you need to create a deep copy:
>>> import copy
>>> a={'a': 1, 'b': 2, 'c': [1,2,3]}
>>> b=copy.deepcopy(a)
>>> b['a']=9
>>> b['c'].append(99)
>>> a
{'a': 1, 'c': [1, 2, 3], 'b': 2}
>>> b
{'a': 9, 'c': [1, 2, 3, 99], 'b': 2}
Is just cause you are making a reference to tdict and not a copy. In order to copy you can either use
newdict['name'+str(i)] = tdict.copy()
or
newdict['name'+str(i)] = dict(tdict)
Hope it helps

Categories