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

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}

Related

Python. How to merge two dictionaries with the same keys?

I have two dicts:
a = {'a': 1, 'b': 2, 'c': 3}
b = {'a': 2, 'd': 4, 'c': 5}
and i want to get:
{'a': 2, 'b': 2, 'c': 5}
i used {**a, **b} but it return:
{'a': 2, 'b': 2, 'c': 5, 'd': 4}
Help me please exclude keys from b which not in a with the simplest and fastest way.
i have python 3.7
You have to filter the elements of the second dict first in order to not add any new elements. I got two possible solutions:
a = {'a': 1, 'b': 2, 'c': 3}
b = {'a': 2, 'd': 4, 'c': 5}
for k,v in b.items():
if (k in a.keys()):
a[k] = v
print(a)
a = {'a': 1, 'b': 2, 'c': 3}
b = {'a': 2, 'd': 4, 'c': 5}
a.update([(k,v) for k, v in b.items() if k in a.keys()])
print(a)
Output for both:
{'a': 2, 'b': 2, 'c': 5}
I think a comprehension is easy enough:
{ i : (b[i] if i in b else a[i]) for i in a }

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}

Merge Two Dictionaries that Share Same Key:Value

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.

Python - Find non mutual items in two dicts

Lets say I have two dictionaries:
a = {'a': 1, 'b': 2, 'c': 3}
b = {'b': 2, 'c': 3, 'd': 4, 'e': 5}
What's the most pythonic way to find the non mutual items between the two of them such that for a and b I would get:
{'a': 1, 'd': 4, 'e': 5}
I had thought:
{key: b[key] for key in b if not a.get(key)}
but that only goes one way (b items not in a) and
a_only = {key: a[key] for key in a if not b.get(key)}.items()
b_only = {key: b[key] for key in b if not a.get(key)}.items()
dict(a_only + b_only)
seams very messy. Any other solutions?
>>> dict(set(a.iteritems()) ^ set(b.iteritems()))
{'a': 1, 'e': 5, 'd': 4}
Try with the symetric difference of set() :
out = {}
for key in set(a.keys()) ^ set(b.keys()):
out[key] = a.get(key, b.get(key))
diff = {key: a[key] for key in a if key not in b}
diff.update((key,b[key]) for key in b if key not in a)
just a bit cheaper version of what you have.
>>> a = {'a': 1, 'b': 2, 'c': 3}
>>> b = {'b': 2, 'c': 3, 'd': 4, 'e': 5}
>>> keys = set(a.keys()).symmetric_difference(set(b.keys()))
>>> result = {}
>>> for k in keys: result[k] = a.get(k, b.get(k))
...
>>> result
{'a': 1, 'e': 5, 'd': 4}
Whether this is less messy than your version is debatable, but at least it doesn't re-implement symmetric_difference.

Categories

Resources