Python3 Determine if two dictionaries are equal [duplicate] - python

This question already has answers here:
Comparing two dictionaries and checking how many (key, value) pairs are equal
(28 answers)
Closed 4 years ago.
This seems trivial, but I cannot find a built-in or simple way to determine if two dictionaries are equal.
What I want is:
a = {'foo': 1, 'bar': 2}
b = {'foo': 1, 'bar': 2}
c = {'bar': 2, 'foo': 1}
d = {'foo': 2, 'bar': 1}
e = {'foo': 1, 'bar': 2, 'baz':3}
f = {'foo': 1}
equal(a, b) # True
equal(a, c) # True - order does not matter
equal(a, d) # False - values do not match
equal(a, e) # False - e has additional elements
equal(a, f) # False - a has additional elements
I could make a short looping script, but I cannot imagine that mine is such a unique use case.

== works
a = dict(one=1, two=2, three=3)
b = {'one': 1, 'two': 2, 'three': 3}
c = dict(zip(['one', 'two', 'three'], [1, 2, 3]))
d = dict([('two', 2), ('one', 1), ('three', 3)])
e = dict({'three': 3, 'one': 1, 'two': 2})
a == b == c == d == e
True
I hope the above example helps you.

The good old == statement works.

Related

Subdivide python dict [duplicate]

This question already has answers here:
How do I create a nested dict from a dict by splitting the keys on a delimiter in python?
(4 answers)
Closed 1 year ago.
I want to write a method which takes a dict in the form of {a: 1, b-c: 2, b-d: 3, e-f-g: 4} and returns {a: 1, b: {c: 2, d: 3}, e: {f: {g: 4}}}. Basically split the keys containing - into subdicts. I've tried to do it iteratively and recursively but I got stuck. Any tips?
You can use collections.defaultdict with recursion:
from collections import defaultdict
d = {'a': 1, 'b.c': 2, 'b.d': 3, 'e.f.g': 4}
def group(d):
nd = defaultdict(list)
for [a, *b], c in d:
nd[a].append([b, c])
return {a:b[0][-1] if not any(j for j, _ in b) else group(b) for a, b in nd.items()}
result = group([[a.split('.'), b] for a, b in d.items()])
Output:
{'a': 1, 'b': {'c': 2, 'd': 3}, 'e': {'f': {'g': 4}}}

Merge 2 dictionaries with higher value for each key [duplicate]

This question already has answers here:
keep highest value of duplicate keys in dicts
(6 answers)
Closed 2 years ago.
I have
dict1 = {a: 1, b: 2, c: 3}
dict2 = {b: 3, c: 2}
How do I merge dict1 and dict2 so that the result dict3 will have {a: 1, b: 3, c: 3}
I know we can merge like this dict3 = {**a, **b}, but is there a condition anywhere I have to write to make it work for my problem?
Here you go:
dict1 = {"a": 1, "b": 2, "c": 3}
dict2 = {"b": 3, "c": 2}
result = {}
for k in dict1.keys() | dict2.keys():
result[k] = max(dict1.get(k, float('-inf')), dict2.get(k,float('-inf')))
print(result)
I am using a get with default: dict1.get(k, DEFAULT) and joining the two keysets with the bitwise OR operator |.
Note that the default of float('-inf') means the result for
dict1 = {"a": -1, "b": 2, "c": 3}
dict2 = {"b": -5, "c": 2}```
becomes {'a': -1, 'b': 2, 'c': 3}.
While for the default of 0 you would get
{'b': 2, 'c': 3, 'a': 0}
Both ways could be considered equally valid responses.
You can merge the dict items into one sequence of tuples, sort them, and then use the dict constructor to create a new dict from the sorted sequence so that items of the same keys but with higher values will override those with lower values:
dict(sorted((*dict1.items(), *dict2.items())))
You could simply loop through them and compare the values, and use dict.setdefault(key, 0) to get around unset values.
dict1 = {'a': 1, 'b': 2, 'c': 3}
dict2 = {'b': 3, 'c': 2}
dict3 = {}
for d in dict1, dict2:
for k, v in d.items():
if v > dict3.setdefault(k, 0):
dict3[k] = v
print(dict3) # -> {'a': 1, 'b': 3, 'c': 3}
defaultdict(int) would also work but I wanted to avoid the import.

User List to Remove keys from Dictionary

What is the best way to get a user to be able to enter a list(or singular) number to remove a string key entry from a dictionary?
so far this is where I am.
My dictionary to remove the values from(the dictionary is generated so will vary).
d = {'Seven': 22, 'Six': 0, 'Three': 35, 'Two': 0, 'Four': 45, 'Five': 34, 'Eight': 0}
1) So how do I get the input is my first query. This was my attempt but failed.
>>> s = raw_input('1 2 3 4')
1 2 3 4
>>> numbers = map(str, s.split())
>>> numbers
[]
>>> s = raw_input('1 2 3 4')
1 2 3 4
>>> numbers = map(int, s.split())
>>> numbers
[]
2) How would I convert the ints to word form? Here the range is limited there will never be greater than 20 entries per dictionary.
So my initial thought was to create a key of sorts to interpret the info.
e = {'One': 1, 'Two': 2, 'Three': 3, 'Four': 4}
and this works not as expected removing only one entry.
>>> e = {'One': 1, 'Two': 2, 'Three': 3, 'Four': 4}
>>> {k:v for k,v in e.items() if v!=(1 and 3)}
{'Four': 4, 'Two': 2, 'One': 1}
My intention is to remove the values from d and not e. Its also not practical as I don't know how many entries the user will enter so using 'and' statements seems wrong.
First, the parameters of raw_input are just for display. You need to enter it yourself:
>>> s = raw_input("Enter a sequence of number: ")
Enter a sequence of number: 1 2 3 4
>>> print s
1 2 3 4
Now, you can just use a list to map it:
m = ['1':'One', '2':'Two', '3':'Three', .., '10':'Ten']
Edit Here is how to convert it:
e = [v for k, v in m.items() if k in s]
Third, dictionary comprehensions (or 'comprehensions' in general) weren't meant to modify an existing object, but to create a new one. The closest you can get is to make it act like a filter, and reassign the results back to d
d = {k:v for k, v in d.items() if k not in e}

Quick inquiry about dict mapping

How can I map single or multiple things to a single element in a dictionary in python.
For example:
dict of str: {str: [str, int]}
myDict = dict()
myDict["myString"] = ["myList", 1, 0.0]
print myDict
Output
{'myString': ['myList', 1, 0.0]}
Example from http://docs.python.org/2/library/stdtypes.html#mapping-types-dict
You can create dict in python in the following ways
>>> a = dict(one=1, two=2, three=3)
>>> b = {'one': 1, 'two': 2, 'three': 3}
>>> c = dict(zip(['one', 'two', 'three'], [1, 2, 3]))
>>> d = dict([('two', 2), ('one', 1), ('three', 3)])
>>> e = dict({'three': 3, 'one': 1, 'two': 2})
>>> a == b == c == d == e
True
You can use a list instead of any of the values (1, 2 or 3)

Counting all the differences in 2 dictionaries and displaying them all

Suppose I have 2 dictionaries:
A = {'banana':10, 'apple':2, 'pear':5, 'orange':3}
B = {'banana':7, 'orange':5, 'strawberry':4, 'blueberry':1, 'kiwi':10}
Now, I need to print all the difference of these dictionaries and display them all (even if there is a key in A that is not in B or otherwise) and of course in absolute values, so the result should be:
c = {'banana':3, 'apple':2, 'pear':5, 'orange':2, 'strawberry':4, 'blueberry':1, 'kiwi':10}
Any ideas? I've seen some posts before but only partial answers to this need.
Using collections.Counter:
from collections import Counter
A = {'banana':10, 'apple':2, 'pear':5, 'orange':3}
B = {'banana':7, 'orange':5, 'strawberry':4, 'blueberry':1, 'kiwi':10}
A_Counter, B_Counter = Counter(A), Counter(B)
print((A_Counter - B_Counter) | (B_Counter - A_Counter))
Output:
Counter({'kiwi': 10, 'pear': 5, 'strawberry': 4, 'banana': 3, 'apple': 2, 'orange': 2, 'blueberry': 1})
In py2x A.viewkeys() | B.viewkeys() will return the union of keys from both A & B, and then you can use a dict comprehension to get the desired result.
In [14]: A = {'banana':10, 'apple':2, 'pear':5, 'orange':3}
In [15]: B = {'banana':7, 'orange':5, 'strawberry':4, 'blueberry':1, 'kiwi':10}
In [16]: {x : abs( A.get(x,0) - B.get(x,0) ) for x in A.viewkeys() | B.viewkeys()}
Out[16]:
{'apple': 2,
'banana': 3,
'blueberry': 1,
'kiwi': 10,
'orange': 2,
'pear': 5,
'strawberry': 4}
For py3x use : A.keys() | B.keys()
For both py2x and py3x: set(A).union(B)

Categories