Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I make a dictionary with multiple keys to one value?

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?

like image 410
IordanouGiannis Avatar asked Apr 12 '12 12:04

IordanouGiannis


People also ask

Can multiple keys in a dictionary have the same value?

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.

Can you have multiple keys for one value Python?

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.

How do you create a dictionary with multiple values per key?

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.

How do you concatenate keys and values in a dictionary?

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.


1 Answers

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 
  • Python's strings and numbers are immutable objects,
  • So, if you want 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).
  • Then, when you modify the object at d['a'], d['b'] changes at same time because they both point to same object.
like image 90
fanlix Avatar answered Sep 19 '22 00:09

fanlix