简体   繁体   中英

Dictionary with tuples key: All tuples with the same first element

I have dictionary in python whose keys are tuples, like:

my-dict={(1,'a'):value1, (1,'b'):value2, (1,'c'):value3, (2,'a'):value4, 
(2,'b'):value5,(3,'a'):value6}

I need to access all values whose keys have the same first argument. For example, I need to access

{(1,'a'):value1, (1,'b'):value2, (1,'c'):value3}  

because all of them have 1 as the first element of the tuple key. One way is to use a for and if :

for key in my-dict:
    if key[0]==1:
       do something

However, my actual dictionary and data are very huge and this method takes a lot of time. Is there any other way to efficiently do this?

You lose out on the benefits of creating a dictionary if you have to search through all its keys again. A good solution would be to create another dictionary That holds all keys which start with the correct first element.

my_dict={(1,'a'):'value1', (1,'b'):'value2', (1,'c'):'value3', (2,'a'):'value4', 
(2,'b'):'value5',(3,'a'):'value6'}

from collections import defaultdict

mapping = defaultdict(list) #You do not need a defaultdict per se, i just find them more graceful when you do not have a certain key.

for k in my_dict:
    mapping[k[0]].append(k)

Mapping now looks like this:

defaultdict(list,
            {1: [(1, 'a'), (1, 'b'), (1, 'c')],
             2: [(2, 'a'), (2, 'b')],
             3: [(3, 'a')]})

Now Just use the dictionary to lookup the keys needed in your original dictionary.

first_element = 1
#Now just use the lookup to do some actions
for key in mapping[first_element]:
    value = my_dict[key]
    print(value)
    #Do something

Output:

value1
value2
value3

The dict built-in type maps hashable values to arbitrary objects. In your dictionary, the tuples (1, 'a') , (1, 'b') , etc. all have different hashes.

You could try using Pandas multi-indexes to accomplish this. Here is a good example.

Alternatively, as one of the comments suggested, a nested dictionary may be more appropriate here. You can convert it from my_dict via

from collections import defaultdict

nested_dict = defaultdict(dict)  # not necessary, but saves a line
for tup_key, value in my_dict.items():
    key1, key2 = tup_key
    nested_dict[key1][key2] = value

Then something like nested_dict[1] would give you

{'a':value1, 'b':value2, 'c':value3}  

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