[英]Check if value exists in a dictionary of dictionaries and get the key(s)?
I have a dictionary of dictionaries: 我有字典词典:
x = {'NIFTY': {11382018: 'NIFTY19SEPFUT', 13177346: 'NIFTY19OCTFUT', 12335874: 'NIFTY19NOVFUT'}}
The dictionary has a lot of other dictionaries inside. 字典中还有很多其他字典。
I want to check whether example: 我想检查一下例子:
y = 11382018
exists in the dictionary, if yes, get the master key
in this case NIFTY
and the value of the above key
ie 'NIFTY19SEPFUT'
在字典中是否存在,如果是,则在这种情况下获取主
key
NIFTY
和上述key
的值,即'NIFTY19SEPFUT'
I can do this in the following way I assume: 我可以按照以下方式进行操作:
for key in x.keys():
di = x[key]
if y in di.keys():
inst = key
cont = di[y]
Just wondering if there is a better way. 只是想知道是否有更好的方法。
I was thinking along the lines of not having to loop over the entire dictionary master keys
我一直在考虑不必遍历整个字典主
keys
思路
A more compact way to retrieve both values of interest would be using a nested dictionary comprehension: 检索两个感兴趣的值的更紧凑的方法是使用嵌套的字典理解:
[(k, sv) for k,v in x.items() for sk,sv in v.items() if sk == y]
# [('NIFTY', 'NIFTY19SEPFUT')]
More compact version (generic): 更紧凑的版本(通用):
[(k, v[y]) for k, v in d.items() if y in v]
Or: 要么:
*next(((k, v[y]) for k, v in d.items() if y in v), 'not found')
if you can guarantee the key is found only in one nested dictionary. 如果可以保证只能在一个嵌套词典中找到该键。 (Note that I have used
d
as dictionary here, simply because that feels more meaningful) (请注意,我在这里使用
d
作为字典,只是因为感觉更有意义)
Code : 代码 :
d = {'NIFTY': {11382018: 'NIFTY19SEPFUT', 13177346: 'NIFTY19OCTFUT', 12335874: 'NIFTY19NOVFUT'}}
y = 11382018
print([(k, v[y]) for k, v in d.items() if y in v])
# or:
# print(*next(((k, v[y]) for k, v in d.items() if y in v), 'not found'))
Straightforwardly (for only 2 levels of nesting): 直接(仅嵌套2级):
x = {'NIFTY': {11382018: 'NIFTY19SEPFUT', 13177346: 'NIFTY19OCTFUT', 12335874: 'NIFTY19NOVFUT'}}
search_key = 11382018
parent_key, value = None, None
for k, inner_d in x.items():
if search_key in inner_d:
parent_key, value = k, inner_d[search_key]
break
print(parent_key, value) # NIFTY NIFTY19SEPFUT
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.