简体   繁体   中英

Python dictionary: set value as the key string

I have a python dictionary and want to set one of the values as the key itself whilst initializing the dict. That is:

dummy = dict(
  Key1 = ["SomeValue1", "Key1"],
  Key2 = ["SomeValue2", "Key2"],
  )

Can this be done programmably? That is, to skip writing the key again and set something like dummy.keys()[currentkeyindex] .

Using dict comprehension :

>>> values = [
...     ["SomeValue1", "Key1"],
...     ["SomeValue2", "Key2"],
... ]
>>> {x[1]: x for x in values}
{'Key2': ['SomeValue2', 'Key2'], 'Key1': ['SomeValue1', 'Key1']}

If you want to keep track of items as well then use defaultdict

>>> from collections import defaultdict                                                                                                      
>>> output = defaultdict(list)
>>> values = [
        ["SomeValue1", "Key1"],
        ["SomeValue2a", "Key2"],
        ["SomeValue2b", "Key2"]
    ]
>>> for x in values:
...     output[x[1]].append(x)
... 
>>> output
defaultdict(<type 'list'>, {
    'Key2': [['SomeValue2a', 'Key2'], ['SomeValue2b', 'Key2']], 
    'Key1': [['SomeValue1', 'Key1']]
})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM