I have several dictionaries like this
dict1 = {0: 33.422, 1: 39.2308, 2: 30.132}
dict2 = {0: 42.2422, 1: 43.342, 2: 42.424}
dict3 = {0: 13.422, 1: 9.2308, 2: 20.132}
I am aware that I could combine them together into one dictionary using the code
dicts = dict1, dict2, dict3
And it returns the result like this
({0: 33.422, 1: 39.2308, 2: 30.132}, {0: 42.2422, 1: 43.342, 2: 42.424}, {0: 13.422, 1: 9.2308, 2: 20.132})
However, what if the dictionaries come sequentially? How can I get the same results? I tried the following code
dicts = {}
dicts = dicts, dict1
dicts = dicts, dict2
dicts = dicts, dict3
But it returns the result like this
((({}, {0: 33.422, 1: 39.2308, 2: 30.132}), {0: 42.2422, 1: 43.342, 2: 42.424}), {0: 13.422, 1: 9.2308, 2: 20.132})
How can we remove the first stuff? I'm using python 3 on windows 7. And all the dictionaries are in a "MyDataFileReader" type under avro package.
If I understand correctly you want a list of dictionaries:
dict1 = {0: 33.422, 1: 39.2308, 2: 30.132}
dict2 = {0: 42.2422, 1: 43.342, 2: 42.424}
dict3 = {0: 13.422, 1: 9.2308, 2: 20.132}
dicts = []
dicts.append(dict1)
dicts.append(dict2)
dicts.append(dict3)
As @MMF already stated in his comment: a, b, c
creates a tuple containing a
, b
and c
(in that order).
What you want to do, is "updating" the dictionary:
dict = {}
dict.update(dict1)
dict.update(dict2)
dict.update(dict3)
Or, if you don't want that dict3
or dict2
overwrite stuff:
dict = {}
dict.update(dict3)
dict.update(dict2)
dict.update(dict1)
Or
def update_without_overwriting(d, x):
dict.update({k: v for k, v in x.items() if k not in d})
dict = {}
update_without_overwriting(dict, dict1)
update_without_overwriting(dict, dict2)
update_without_overwriting(dict, dict3)
If you just want a tuple containing all dicts however, use this:
dict = dict1, dict2
dict += dict3,
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With