I am trying to get the keys whose values differ in both dictionaries
e.g:
items1=['a','b','c']
price1=[1,2,3]
dictA= dict(zip(items1, price1))
items2=['a','b']
price2=[1,3]
dictB=dict(zip(items2,price2))
so the difference will be ['b'] as this key is the only difference
i tried using set(dictA.items()).symmetric_difference(dictB.items()), but this is also returning the key:value {'c':3}
Iterate over the common keys, and drop keys having matching values in dictA and dictB:
In [3]: {key for key in dictA.keys() & dictB if dictA[key] != dictB[key]}
Out[3]: {'b'}
You'll have to iterate over the intersection.
delta = [k for k in (set(dictA) & set(dictB)) if (dictB[k] - dictA[k])]
Related
I have a dictionary like this,
d = {1:'a', 2:'b', 3:'c', 4:'d'}
Now I want to filter the dictionary where the key should be more than 1 and less than 4 so the dictionary will be,
d = {2:'b', 3:'c'}
I could do this using a for loop, iterating over all the keys. but the execution time will be more looking for some fastest way to do this more efficiently in pythonic way.
you can try below code:
d = {k:v for k,v in d.items() if 1<k<4}
Pythonic way would be to use a dictionary comprehension:
{key: value for key, value in d.items() if 1 < key < 4}
It's readable enough: for each key and value in the items of the dictionary, keep those key: value pairs that have their keys between 1 and 4.
More pythonic way would be a dictionary comprehension
d = {k: v for (k, v) in d.items() if k > 1 and k < 4}
If the efficiency is a bottleneck, you may want to try to use some tree based structure instead of a dictionary that is hash based.
Python dictionaries use hashes of their keys to efficiently lookup and store data. Unfortunately, that means that they don't allow you use the numeric properties of those keys to select data (the way you might be able to do using a slice to index a list).
So I think the best way to do what you want is probably just a dictionary comprehension that tests each key against your boundary values:
d = {key: value for key, value in d.items() if 1 < key < 4}
I have a dictionary - where the values are dictionaries themselves.
How do I extract the unique set of the values from the child dictionaries in the most efficient way?
{ 'A':{'A1':'A1V','B2':'A2V'..},
'B':{'B1':'B1V','B2':'B2V'...},
...}
Expected output:
['A1V','A2V','B1V','B2V'...]
In a single line:
>>> [val for dct in x.values() for val in dct.values()]
['A1V', 'A2V', 'B2V', 'B1V']
Assuming you named your dict of dict x.
You mentioned unique, in that case replace the list-comprehension by a set-comprehension:
>>> {val for dct in x.values() for val in dct.values()} # curly braces!
{'A1V', 'A2V', 'B1V', 'B2V'}
uniques = set()
for ukey, uvalue in outerdic.items():
for lkey, lvalue in uvalue.items():
uniques.add(lvalue)
print uniques
Using a set should work. New to stackoverflow, trying to figure out how syntax highlighting works.
This assumes that the dictionary is called outerdic.
dictionary = { 'A':{'A1':'A1V','B2':'A2V'},'B':{'B1':'B1V','B2':'B2V'}}
for key in dictionary.keys() :
dict1 = dictionary[key]
for key1 in dict1.keys():
print(dict1[key1])
Tried to keep it as simple as possible.
I have four dictionaries of similar length.
I want to:
get those keys that are matched between the four.
Iterate over certain value in each dictionary which I will compare later and do some arithmetic operations.
I have done that using nested loop (four loops) but that doesn't look efficient at all. I want to make this code more efficient and elegant.
I want to do that without doing nested loop:
d1 = {1:18:[['28','Y','N'],['108','A','M'],...]
d2,d3 and d4 are the same thing expect different values but some will have same keys
for k, v in di1.iteritems():
for v1 in v:
for k2,v2 in di2.iteritems():
for va2 in v2:
if k == k2:
for k3,v3 in di3.iteritems():
for va3 in v3:
if k2 == k3:
for k4,v4 in di4.iteritems():
for va4 in v4:
if k3==k4 and k==k4 and k==k3:
# do some arithmetics on dictionary's values for all four dictionaries
Thanks a lot in advance.
if they have the same keys, then di1.keys() == di2.keys() == di3.keys() == di4.keys().
keys = di1.keys()
for k in keys:
# do something with di1[k] di2[k] di3[k] di4[k]
if they do not all have the keys, build the union set of the keys, and check which dict has each key, using in:
keys = set(di1.keys()) | set(di2.keys()) | set(di3.keys()) | set(di4.keys())
for k in keys:
if k in di1:
# di1 has the key
if k in di2:
# di2 has the key
if k in di1 and k in di2:
# do something with di1[k] and di2[k]
# ...
1) I assume "get those keys that are matched between the four" means you want to find keys that are present in ALL four dictionaries. One way to achieve this is to take the intersection of the four sets of keys.
common_keys = set(d1.keys()) & set(d2.keys()) & set(d3.keys()) & set(d4.keys())
2) Iterate over the common keys and "do some arithmetics on dictionary's values for all four dictionaries":
for key in common_keys:
for dict in [d1, d2, d3, d4]:
# do something with dict[key]...
You can also use list comprehensions if you wish to avoid nested loops, e.g. generate a list of (key, list of tuples) pairs and operate on that later:
common_keys_vals = [(key, [dict[key] for dict in [d1, d2, d3, d4]])
for key in common_keys]
I have 2 dictionary which contain the same keys but the value pairs are different. Let's make dictA and dictB represent the two dictionaries in question.
dictA = {'key1':'Joe', 'key2':'Bob'}
dictB = {'key1':'Smith', 'key2':'Johnson'}
Currently, I am creating a new dictionary based the common occurring keys through a nested if statement. In doing so, the values that share a key are contained within a list, in the new dictionary. See this done below:
dictAB = {} # Create a new dictionary
# Create a list container for dictionary values
for key in dictA.keys():
dictAB[key] = []
# Iterate through keys in both dictionaries
# Find matching keys and append the respective values to the list container
for key, value in dictA.iteritems():
for key2, value2 in dictB.iteritems():
if key == key2:
dictAB[key].append(value)
dictAB[key].append(value2)
else:
pass
How can this be made into a more clean structure using python dictionary comprehension?
Use sets or key views (python 2.7):
dictAB = {k: [dictA[k], dictB[k]] for k in dictA.viewkeys() & dictB.viewkeys()}
Before 2.7:
dictAB = dict((k, [dictA[k], dictB[k]]) for k in set(dictA) & set(dictB))
In python 3, you can use the .keys method for such operations directly, as they are implemented as views:
dictAB = {k: [dictA[k], dictB[k]] for k in dictA.keys() & dictB.keys()}
Demo (python 2.7):
>>> dictA = {'key1':'Joe', 'key2':'Bob'}
>>> dictB = {'key1':'Smith', 'key2':'Johnson'}
>>> dictAB = {k: [dictA[k], dictB[k]] for k in dictA.viewkeys() & dictB.viewkeys()}
>>> print dictAB
{'key2': ['Bob', 'Johnson'], 'key1': ['Joe', 'Smith']}
The & operator on either two sets or on a dict view creates the intersection of both sets; all keys that are present in both sets.
By using an intersection of the keys, this code will work even if either dictA or dictB has keys that do not appear in the other dictionary. If you are absolutely sure the keys will always match, you could just iterate over either dict directly without the intersection:
dictAB = {k: [dictA[k], dictB[k]] for k in dictA}
dictAB = { key: [dictA[key],dictB[key]] for key in dictA if key in dictB }
suppose I have a dictionary whose keys are strings. How can I efficiently make a new dictionary from that which contains only the keys present in some list?
for example:
# a dictionary mapping strings to stuff
mydict = {'quux': ...,
'bar': ...,
'foo': ...}
# list of keys to be selected from mydict
keys_to_select = ['foo', 'bar', ...]
The way I came up with is:
filtered_mydict = [mydict[k] for k in mydict.keys() \
if k in keys_to_select]
but I think this is highly inefficient because: (1) it requires enumerating the keys with keys(), (2) it requires looking up k in keys_to_select each time. at least one of these can be avoided, I would think. any ideas? I can use scipy/numpy too if needed.
dict((k, mydict[k]) for k in keys_to_select)
if you know all the keys to select are also keys in mydict; if that's not the case,
dict((k, mydict[k]) for k in keys_to_select if k in mydict)