0

was wondering if it was possible to have a value with multiple keys and vice versa in a python dictionary. I am a beginner so i am assuming this should be an easy solve, just need the correct formatting.

Was looking for something like this:

   dictionary = {
                '1','2','3': "blue"
                '4': "blue","green"
                }
6
  • Presumably you're looking for dictionary['1'] == dictionary['2'] == dictionary['3']? Then no, there's no shorthand for that. Commented Jul 24, 2017 at 18:34
  • 1
    What exactly are you trying to achieve? It's probably better to talk about what exact use you're trying to achieve, because as described this is neither possible nor sensible. Commented Jul 24, 2017 at 18:34
  • No, the numbers are representing keys in the dictionary and the colors are values. Was wondering if there was an easier way to assign the same value to different keys instead of doing { '1': "blue", '2':"blue, '3':'blue} and instead do something like { '1','2','3':"blue"} Commented Jul 24, 2017 at 18:39
  • You definitely can't have multiple values for a key, that defeats the point of a dictionary. You can, on the other hand, have a list as a value, which might suit your needs. Commented Jul 24, 2017 at 18:41
  • You can switch the keys and values and have a list of something mapped by a key. But you cannot have multiple values for keys Commented Jul 24, 2017 at 18:42

1 Answer 1

3

dict can only have one value/name for one key :

>>> dic={}
>>> dic['1']=12
>>> dic
{'1': 12}

other way it create a tuple as key :

>>> dic={}
>>> dic['1','2']=12
>>> dic
{('1', '2'): 12}

a dictionary is one key that can contain what ever you want, but in your example if value are key and colors values, you should have dic={1: ['blue'], 2: ['blue'], 3: ['blue'], 4: ['blue', 'green']}:

but you can built it in a shorter way.

one option :

>>> dic={i:["blue"] for i in [1,2,3]}
>>> dic[4]=["blue", "green"]
>>> dic
{1: ['blue'], 2: ['blue'], 3: ['blue'], 4: ['blue', 'green']}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.