A dict associates exactly one value with a particular key, so your original dict d
would see two different values for the key "x" (first 1 and then 3), and the last one would replace previous ones. If you have access to an interactive Python session, this looks like:
$ python
Python 3.9.1 (default, Dec 13 2020, 11:55:53)
[GCC 10.2.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> d = {"x": 1, "y": 2, "x": 3, "z": 5}
>>> d
{'x': 3, 'y': 2, 'z': 5}
(The d
by itself there just asks Python to use print
to display the current value, as if you had called print(d)
.)
So at this point you have some options. You could just define a dict to contain the eventual values you want: {"x":(1,3),"y":(2,),"z":(5,)}
. Or, if you actually have a source of a stream or list of pairs of values that you want to process into a dict using a function like the one you describe, we can do that, too, but we need to use something like a list of tuples as the input, rather than a dict: l = [("x", 1), ("y", 2), ("x", 3), ("z", 5)]
. With that new notion of the input, we could write a function that in some way processes each element of that list and compiles those elements into a particular dict. Here's one way that could look (without any error handling):
from functools import reduce
def add_tuple_to_dict(d, t): # here `d` is the dict and `t` is the tuple
if t[0] in d:
d[t[0]].append(t[1])
else:
d[t[0]] = [t[1],]
return d
def invert_d(list_of_tuples):
return reduce(add_tuple_to_dict, list_of_tuples, {})
Edit: after submitting the above, I now realize you do actually want to invert your dict, which could look like this, instead:
from functools import reduce
def add_tuple_to_dict(d, t): # here `d` is the dict and `t` is the tuple
if t[1] in d:
d[t[1]].append(t[0])
else:
d[t[1]] = [t[0],]
return d
def invert_d(d):
return reduce(add_tuple_to_dict, d.items(), {})