I'm trying to do a dictionary which include countries GMT time (int number) for example I have a dict and I want to get the value of it, I tried this code:
countires= {('Jerusalem', 'Athens', 'Bucharest'):2 ,('Bahrain','Qatar'):3}
print(countires.get('Athens'))
and the output is:
None
How I can get result 2?
CodePudding user response:
IIUC, You need create temp dict
that have seperate key and search what you want like below:
>>> countires= {('Jerusalem', 'Athens', 'Bucharest'):2 ,('Bahrain','Qatar'):3}
>>> dct = {k:value for key,value in countires.items() for k in key}
>>> print(dct.get('Athens'))
2
If you want to use your original dictionary
you can define function
and search in keys like below:
>>> def search_multi_key(search, dct):
... for key, value in dct.items():
... if search in key:
... return value
... return None
>>> search_multi_key('Athens', countires)
2
CodePudding user response:
One approach is to create a new dictionary, that uses as key each of the elements of the tuples:
countries= {('Jerusalem', 'Athens', 'Bucharest'):2 , ('Bahrain', 'Qatar'):3}
cities = { key : value for keys, value in countries.items() for key in keys }
print(cities.get('Athens'))
Output
2