Merge Two Dictionaries that Share Same Key:Value - python

I know this can be done with lists, but I'm just trying to figure out how to do this with dictionaries.
Basically, it'll go like this:
dict1 = {'a': 10, 'b': 12, 'c': 9}
dict2 = {'a': 10, 'b': 3, 'c': 9}
def intersect(dict1, dict2):
combinDict = dict()
....
print(combinDict)
{'a': 10, 'c':9}
So I only want the keys with the same value added into a new dictionary.
Any help?

You want the intersection of the items:
dict1 = {'a': 10, 'b': 12, 'c': 9}
dict2 = {'a': 10, 'b': 3, 'c': 9}
print dict(dict1.viewitems() & dict2.items())
{'a': 10, 'c': 9}
For python 3 you just want to use items:
dict(dict1.items() & dict2.items())
dict1.items() & dict2.items() returns a set of key/value pairings that are common to both dicts:
In [4]: dict1.viewitems() & dict2.items()
Out[4]: {('a', 10), ('c', 9)}
Then we simply call the dict constructor on that.

Another way to do this would be to use a dict comprehension:
In [1]: dict1 = {'a': 10, 'b': 12, 'c': 9}
In [2]: dict2 = {'a': 10, 'b': 3, 'c': 9}
In [3]: {key: dict1[key] for key in dict1 if dict1[key] == dict2.get(key)}
Out[3]: {'a': 10, 'c': 9}
This should be teeny weeny bit faster, though that wouldn't matter for regular dictionaries.

Related

Is there any way to change the keys (not Values) in the dictionary in Python?

I want to change just Keys (not Values) in a Dictionary in Python. Is there any way to do that?
You can pop the value of the old key and reassign:
d = {'A': 1, 'B': 2, 'C': 3}
d['b'] = d.pop('B')
print(d)
# {'A': 1, 'C': 3, 'b': 2}
Note that this won't maintain the order of the keys (python 3.6+). The renamed key will be instead at the end.
maintaining order
If order is important you need to create a new dictionary
d = {'A': 1, 'B': 2, 'C': 3}
rename = {'B': 'b', 'A': 'a'}
d = {rename.get(k, k): v for k,v in d.items()}
print(d)
# {'a': 1, 'b': 2, 'C': 3}
in place modification while maintaining order
If you want to modify the dictionary in place (i.e. not creating a new object), you need to pop and reinsert all keys in order:
d = {'A': 1, 'B': 2, 'C': 3}
rename = {'B': 'b', 'A': 'a'}
keys = list(d)
for k in keys:
d[rename.get(k, k)] = d.pop(k)
print(d)
{'a': 1, 'b': 2, 'C': 3}

Python - Update a dictionary's value with another dictionary [duplicate]

This question already has answers here:
Python Dictionary: How to update dictionary value, base on key - using separate dictionary keys
(2 answers)
Closed 1 year ago.
I have the following 2 dictionaries
a = {'a': 1, 'b': 2, 'c': 3}
b = {1: 11, 2: 22}
And I'd like to modify a into
a = {'a': 11, 'b': 22, 'c': 3}
How do I achieve this result?
You might use following dict-comprehension
a = {'a': 1, 'b': 2, 'c': 3}
b = {1: 11, 2: 22}
a = {k:b.get(v,v) for k,v in a.items()}
print(a)
output
{'a': 11, 'b': 22, 'c': 3}
Note usage of .get(v,v) so if there is not key in b original value is retained.
you can try dict comprehension
{k1: b.get(v1, v1) for k1,v1 in a.items()}
{'a': 11, 'b': 22, 'c': 3}
Try this:
a = {k: b.get(v, v) for k, v in a.items()}
try this:
a = {'a': 1, 'b': 2, 'c': 3}
b = {1: 11, 2: 22}
for k,v in a.items():
a[k] = b.get(v, v)
print(a)
Output:
{'a': 11, 'b': 22, 'c': 3}

Q: How get two value in two dictionary with same keys in python

i'm trying my code. I'm confused..How to combine these 2 dictionaries so that the value of the results is like this?
1 A 18
5 B 14
3 C 15
7 D 20
for code
d= {'A': 1, 'B': 5, 'C': 3, 'D': 7}
e= {'A': 18, 'B': 14, 'C': 15, 'D': 20}
for k,v in d.items():
print (v)
for i,(k, v) in enumerate(e.items()):
print(i,k, v)
i don't understand. Please help me. Thanks!
You can do this:
d = {'A': 1, 'B': 5, 'C': 3, 'D': 7}
e = {'A': 18, 'B': 14, 'C': 15, 'D': 20}
for k in sorted(d.keys() & e.keys()):
print(d[k], k, e[k])
The & ensures that we only use the keys present in both d and e.
Note that we need the sorted call to ensure that the dicts are indexed alphabetically in the situation where the dict keys aren't alphabetically inserted in the first place.
d= {'A': 1, 'B': 5, 'C': 3, 'D': 7}
e= {'A': 18, 'B': 14, 'C': 15, 'D': 20}
for i in d.keys():
print(d[i],i,e[i])
As the key in both dictionaries are same, so if you access one key you can easily access values from both the dictionaries and can print it in any order/format.
d= {'A': 1, 'B': 5, 'C': 3, 'D': 7}
e= {'A': 18, 'B': 14, 'C': 15, 'D': 20}
final_dictionary = {x: d.get(x, 0) + e.get(x, 0)
for x in set(d).union(e)}
print("final dictionary", str(final_dictionary))

Get values from many dictionaries by hierarchy

I have 4 dictionaries, let's call them:
dict1 , dict2 , dict3 , dict4
Example:
dict1 = {'A': 1, 'B':2}
dict2 = {'A': 3, 'C':4}
dict3 = {'B': 5, 'D':6}
dict4 = {'A': 7, 'B':8, 'C': 9, 'D':10, 'E':11}
Each dictionary level is "stronger" than those who come after it. As in, A found in dict1 will be 'stronger' than A found in dict2 in terms of precedence.
Is there a short, elegant script to create a new dictionary, assembled from all four, where each key is taken from the "strongest" dictionary that contains that key?
The result should be: dict = {'A':1, 'B':2, 'C':4, 'D:6', 'E':11}
I think the easiest/clearest approach here would be to create a new dictionary then use its update method, which overwrites existing keys. Something like this makes the precedence pretty obvious:
>>> x = {}
>>> x.update(dict4)
>>> x.update(dict3)
>>> x.update(dict2)
>>> x.update(dict1)
>>> x
{'A': 1, 'B': 2, 'C': 4, 'D': 6, 'E': 11}
Docs
You could of course make a utility of some sort for this, something like:
>>> def collapse(*dicts):
... x = {}
... for dict in dicts:
... x.update(dict)
... return x
...
>>>
>>> collapse(dict4, dict3, dict2, dict1)
{'A': 1, 'B': 2, 'C': 4, 'D': 6, 'E': 11}
(Though you'd need to remember to pass the dictionaries in the correct order.)
You could do the following (works on python 3.5 and newer):
result = {**dict4, **dict3, **dict2, **dict1}
Here's a fairly simple way for an arbitrary number of dictionaries:
dict1 = {'A': 1, 'B':2}
dict2 = {'A': 3, 'C':4}
dict3 = {'B': 5, 'D':6}
dict4 = {'A': 7, 'B':8, 'C': 9, 'D':10, 'E':11}
# strongest dictionary last
dictionaries = [dict4, dict3, dict2, dict1]
dict(i for d in dictionaries for i in d.items())
Output:
{'A': 1, 'B': 2, 'C': 4, 'D': 6, 'E': 11}
You probably want a ChainMap, which is perfect for simulating scope.
>>> import collections
>>> cm = collections.ChainMap(dict1, dict2, dict3, dict4)
>>> dict(cm)
{'A': 1, 'B': 2, 'C': 4, 'D': 6, 'E': 11}
>>> cm['A'] = 'foo'
>>> cm
ChainMap({'A': 'foo', 'B': 2}, {'A': 3, 'C': 4}, {'B': 5, 'D': 6}, {'A': 7, 'B': 8, 'C': 9, 'D': 10, 'E': 11})
>>> dict1
{'A': 'foo', 'B': 2}

Sorting list of dicts by value of a key (or default-value, if key is missing)

Imagine that you have to sort a list of dicts, by the value of a particular key. Note that the key might be missing from some of the dicts, in which case you default to the value of that key to being 0.
sample input
input = [{'a': 1, 'b': 2}, {'a': 10, 'b': 3}, {'b': 5}]
sample output (sorted by value of key 'a')
[{'b': 5}, {'a': 1, 'b': 2}, {'a': 10, 'b': 3}]
note that {'b': 5} is first in the sort-order because it has the lowest value for 'a' (0)
I would've used input.sort(key=operator.itemgetter('a')), if all the dicts were guaranteed to have the key 'a'. Or I could convert the input dicts to collections.defaultdict and then sort.
Is there a way to do this in-place without having to creating new dicts or updating the existing dicts? Can operator.itemgetter handle missing keys?
>>> items = [{'a': 1, 'b': 2}, {'a': 10, 'b': 3}, {'b': 5}]
>>> sorted(items, key=lambda d: d.get('a', 0))
[{'b': 5}, {'a': 1, 'b': 2}, {'a': 10, 'b': 3}]
Or to update the existing dictionary in-place
items.sort(key=lambda d: d.get('a', 0))
Or if in sorted:
>>> items = [{'a': 1, 'b': 2}, {'a': 10, 'b': 3}, {'b': 5}]
>>> sorted(items,key=lambda x: x['a'] if 'a' in x else 0)
[{'b': 5}, {'a': 1, 'b': 2}, {'a': 10, 'b': 3}]
>>>

Categories

Resources