a = {'name1':'tom'}
b = {'name2':'harry'}
c = {'name3':'peter'}
For a given key, I would like to get the name of the dictionary contains it.
Example:
If i give 'name2', I would like to get b as the result
Thanks
a = {'name1':'tom'}
b = {'name2':'harry'}
c = {'name3':'peter'}
For a given key, I would like to get the name of the dictionary contains it.
Example:
If i give 'name2', I would like to get b as the result
Thanks
You can use next
to return the next value in a sequence, and filter it based on some criteria:
key = 'name2'
found = next(d for d in (a, b, c)
if key in d)
a = {'name1':'tom'}
b = {'name2':'harry'}
c = {'name3':'peter'}
name = 'name2'
for k, v in locals().copy().items():
if isinstance(v, dict):
if name in v:
print('"{}" contains id dict "{}"'.format(name, k))
# "name2" contains in dict "b"
But usually you shouldn't do it. Create dict of dicts and iterate through it:
ds = {
'a': {'name1':'tom'},
'b': {'name2':'harry'},
'c': {'name3':'peter'},
}
name = 'name2'
for k, v in ds.items():
if name in v:
print('"{}" contains id dict "{}"'.format(name, k))
# "name2" contains in dict "b"
Since you said you would like to get b
back as a variable, one way I can think of doing this is making a list of your dictionaries and enumerating through them.
a = {'name1':'tom'}
b = {'name2':'harry'}
c = {'name3':'peter'}
name = 'name2'
dicts = list(a,b,c)
required_dic = findDict(dicts)
def findDict(dicts):
for obj in dicts:
if "name2" in obj:
return obj
but as @germn said, a better idea would be to create a nested dictionary.
Let's say that you put references to your dictionaries in an iterable
l = [da, db, dc, ...]
that you initialize the reference to one of your dictionaries to an invalid value
d = None
to find which dictionary has word
as a key it's simply
for _ in l:
if word in _:
d = _
break
at this point, either you didn't find word
in any of your dicts and d
is hence still equal to None
, or you've found the dictionary containing word
and you can do everything you want to it
if d:
...
You may create a mapping dict, which maps the key to variable binding:
{"name1" : a, "name2" : b, "name3" : c}