Reputation: 179
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?
Upvotes: 3
Views: 2621
Reputation: 6246
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
Upvotes: 3
Reputation: 2950
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}
Upvotes: 3