Home > Back-end >  when I use a tuple for a key of a dictionary, can I search data with only one element of the tuple k
when I use a tuple for a key of a dictionary, can I search data with only one element of the tuple k

Time:11-27

Let's assume that there's a dictionary variable 'dict' like below. with tuple type keys in this case.

      dict = {(a,2019): 6, (a,2020): 7 , (a,2021):8, (a,2022):9, (b,2020):8, (b,2021):10}

And then I want to search all values with keys that has 'a' for the first element of the key. So after search I want to put the result set into a list 'result'. result will have the values like below.

      result = [6,7,8,9]  

I would be able to get values like below

result.append(dict.get((a,2019)))

result.append(dict.get((a,2020))) ....

but I wanted to search data by matching only once for example using regex in this case like

result=dict.get((a, "\d{4}")) Obviously, this doesn't work.

I just want to know if there's a way that I can search data by matching only one element of tuple type keys in this case.

CodePudding user response:

You may just want a dictionary of dictionaries. If you define:

from collections import defaultdict

mydict = defaultdict(dict)

Then you can write things like mydict['a'][2010] = 100 and have what you expect.

Looking at the value of mydict['a'] will returns dictionary of all years in which the first part of the key is 'a'.

CodePudding user response:

How about a list comprehension to see if a is in the key of you dictionary?

mydict = {(a,2019): 6, (a,2020): 7 , (a,2021):8, (a,2022):9, (b,2020):8, (b,2021):10}

result = [v for k,v in mydict.items() if a in k]
# [6, 7, 8, 9]

CodePudding user response:

You can use list comprehension:

dct = {('a',2019): 6, ('a',2020): 7 , ('a',2021):8, ('a',2022):9, ('b',2020):8, ('b',2021):10}

result = [v for k, v in dct.items() if k[0] == 'a']
print(result) # [6, 7, 8, 9]
  • Related