A dictionary in Python consist of key-value-pairs. So in your example, one key would be '950001,959070,959071,959072,950908,959073'
. In my explanations below, I will call 950001
, 959070
and so on just "numbers".
Method 1: You could write a loop over all keys of your dict
and split each key into a list at every comma ,
with str.split
. Your list then contains your numbers and you can check if your requested number n
is in there:
mydict = {'950001,959070,959071,959072,950908,959073': 'value1', '400856,400857,400858,400859,400860,400861': 'value2', '920100': 'value3', '950107,950109,950108': 'value4'}
n = '950001'
for key in mydict:
if n in key.split(','):
print(mydict[key])
Which prints:
value1
Method 2: Alternatively, you could convert your dictionary mydict
into a new dictionary new_dict
so every number gets its own key:
mydict = {'950001,959070,959071,959072,950908,959073': 'value1', '400856,400857,400858,400859,400860,400861': 'value2', '920100': 'value3', '950107,950109,950108': 'value4'}
new_dict = {}
for key in mydict:
for new_key in key.split(','):
new_dict[new_key] = mydict[key]
print(new_dict)
Which prints:
{'950001': 'value1', '959070': 'value1', '959071': 'value1', '959072': 'value1', '950908': 'value1', '959073': 'value1', '400856': 'value2', '400857': 'value2', '400858': 'value2', '400859': 'value2', '400860': 'value2', '400861': 'value2', '920100': 'value3', '950107': 'value4', '950109': 'value4', '950108': 'value4'}
Then you can access your value just like you said with new_dict['950001']
.
The code above is written with emphasis on clarity. Depending on your use case, you could write a function and/or use a dict
comprehension to make your code look nicer if you're comfortable with that:
mydict = {'950001,959070,959071,959072,950908,959073': 'value1', '400856,400857,400858,400859,400860,400861': 'value2', '920100': 'value3', '950107,950109,950108': 'value4'}
new_dict = {nk: v for k, v in mydict.items() for nk in k.split(',')}
print(new_dict['950001'])