简体   繁体   English

如何动态打印dict键值?

[英]How to print dict key value dynamically?

I'm trying to print a dict key value dynamically.我正在尝试动态打印 dict 键值。

EX:前任:

print(data['waninfo']['1']['user']['_value']) ->"teste"
print(data['waninfo']['1']['pw']['_value']) -> "teste123"

As we see the key 'waninfo' and '1' are fixed and i would like to use the keys after dynamically, like this:正如我们看到的关键'waninfo'和'1'是固定的,我想动态地使用这些键,如下所示:

fixedKey = "['user']['_value']"
print(data['waninfo']['1']+fixedKey)

How can i do this?我怎样才能做到这一点?

If there's a constant number of keys, it might be easiest to just declare separate variables for them:如果键的数量是恒定的,那么为它们声明单独的变量可能是最简单的:

key1, key2 = 'user', '_value'
print(data['waninfo']['1'][key1][key2])

If you have a variable (or very large) number of keys, use an iterable and then iterate over it to do the nested lookups:如果您有可变(或非常大)数量的键,请使用可迭代对象,然后对其进行迭代以进行嵌套查找:

keys = 'user', '_value'
val = data['waninfo']['1']
for key in keys:
    val = val[key]
print(val)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM