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:
Code golf?
yesindices = [1,2,3,22,34,33]
noindices = [4,8,9]
dict (zip(yesindices, ['yes' for i in yesindices]) + zip(noindices, ['no' for i in noindices]))
yields
{1: 'yes', 2: 'yes', 3: 'yes', 4: 'no', 33: 'yes', 8: 'no', 9: 'no', 34: 'yes', 22: 'yes'}
Try to iterate through the dict items.
{key: value for key, value in your_dict.iteritems()}
{key: value for key, value in your_dict.items()}
d = {'READY': 'GPLR2_95',
95: 'GPLR2_95',
'CHARGING': 'GPLR3_99',
'PROTECTION': 'GPLR3_100',
'CONNECTED': 'GPLR3_101',
'ERROR':'GPLR3_102'}
What's wrong with breaking this into multiple lines (as above)? Is the point saving typing or saving vertical space? Something else?
BTW, it feels really strange to have keys that are a mix of numbers and strings.
note: I wrote this as an answer instead of a comment because I wanted to show formatted code on multiple lines.
dict((x, {4: 'no'}.get(x, 'yes')) for x in range(1, 5))
Or in 3.x:
{x: {4: 'no'}.get(x, 'yes') for x in range(1, 5)}
For your case
dict([(_, 'yes') for _ in range(1,4)], **{4:'no'})
And if you need multiple keys for 'yes'
and 'no'
>>> from itertools import chain
>>> dict(chain([(_, 'yes') for _ in range(1,4)], [(_, 'no') for _ in range(4, 10)]))
{1: 'yes', 2: 'yes', 3: 'yes', 4: 'no', 5: 'no', 6: 'no', 7: 'no', 8: 'no', 9: 'no'}
Not so great, but works.
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'}