I have a question about a dictionary I want to make. My goal is to have multiple keys to a single value, like below:
dictionary = {('a', 'b'): 1, ('c', 'd'): 2} assert dictionary['a'] == 1 assert dictionary['b'] == 1
Any ideas?
Answer. No, each key in a dictionary should be unique. You can't have two keys with the same value. Attempting to use the same key again will just overwrite the previous value stored.
In Python dictionary, if you want to display multiple keys with the same value then you have to use the concept of for loop and list comprehension method. Here we create a list and assign them a value 2 which means the keys will display the same name two times.
In python, if we want a dictionary in which one key has multiple values, then we need to associate an object with each key as value. This value object should be capable of having various values inside it. We can either use a tuple or a list as a value in the dictionary to associate multiple values with a key.
To concatenate the key and value of the dictionary . join is used and ',' separator is also used. The . items() method returns the view object that returns an object containing the key-value pair.
I guess you mean this:
class Value: def __init__(self, v=None): self.v = v v1 = Value(1) v2 = Value(2) d = {'a': v1, 'b': v1, 'c': v2, 'd': v2} d['a'].v += 1 d['b'].v == 2 # True
d['a']
and d['b']
to point to the same value that "updates" as it changes, make the value refer to a mutable object (user-defined class like above, or a dict
, list
, set
).d['a']
, d['b']
changes at same time because they both point to same object.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