Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python dictionary creation syntax

I'm wondering if there's any way to populate a dictionary such that you have multiple keys mapping to the same value that's less verbose than say:

d = {1:'yes', 2:'yes', 3:'yes', 4:'no'} 

I'm thinking something along the lines of:

d = {*(1,2,3):'yes', 4:'no'} 

which is obviously a syntax error.

Is there a reasonably simple method of doing this without TOO much obfuscation? (I'm not playing code golf, but I also don't need to write essentially the same thing over and over. However, any code-golf related answers would be appreciated as well since code-golf is awesome =]).

Edit:

I probably picked a bad example. This is what I'm trying to do:

d = {*('READY', 95): 'GPLR2_95', 'CHARGING': 'GPLR3_99', 'PROTECTION': 'GPLR3_100', 'CONNECTED': 'GPLR3_101', 'ERROR':'GPLR3_102'} 

What I would expect this to expand to is:

d = {'READY':'GPLR2_95', 95: 'GPLR2_95', ...} 

Edit->Edit:

I know this is stupid and totally unnecessary, but my goal is to make this declaration on a single line. This obviously shouldn't limit any responses and writing code just because it fits on 1 line is stupid. But I'm writing a module level constant dict that would be nice if it was a single liner.

like image 602
Falmarri Avatar asked May 31 '11 18:05

Falmarri


People also ask

What is the syntax for creating a dictionary in Python?

In Python, a dictionary can be created by placing a sequence of elements within curly {} braces, separated by 'comma'. Dictionary holds pairs of values, one being the Key and the other corresponding pair element being its Key:value.

How do you create a data dictionary in Python?

To create a Python dictionary, we pass a sequence of items (entries) inside curly braces {} and separate them using a comma ( , ). Each entry consists of a key and a value, also known as a key-value pair. Note: The values can belong to any data type and they can repeat, but the keys must remain unique.

What is the correct syntax to create and print the dictionary in Python?

About Dictionaries in Python To create a Dictionary, use {} curly brackets to construct the dictionary and [] square brackets to index it. Separate the key and value with colons : and with commas , between each pair. As with lists we can print out the dictionary by printing the reference to it.


1 Answers

You could turn it around:

>>> d1 = {"yes": [1,2,3], "no": [4]} 

and then "invert" that dictionary:

>>> d2 = {value:key for key in d1 for value in d1[key]} >>> d2 {1: 'yes', 2: 'yes', 3: 'yes', 4: 'no'} 
like image 152
Tim Pietzcker Avatar answered Oct 07 '22 06:10

Tim Pietzcker