在python中使用dict键作为不同的dict中的值 [英] Using dict keys in python as values in a different dict
问题描述
我想创建一个翻译类型的dict,它将为我创建的一个dict中的密钥分配属于嵌套的不同分组中的键的值。我遇到的问题是,我不能创建一个代表嵌套的dict键的值,而不必将其转换为字符串或其他数据类型,当我尝试使用字符串作为嵌套dict的索引时,我得到一个索引错误。理想情况下,我的dict将如下所示:
I would like to create a "translator" type of dict that would assign values that are keys in different dicts, which are nested, to keys in a dict that I created. The problem I run into is that I can't create a value that represents a nested dict key without having to convert that to a string or some other data type, and when I try to use a string as an index to the nested dict, I get an index error. Ideally, my dict would look something like this:
new_dict{
"new_key_1" : ['subdict1']['subdict2']['old_key_1'],
"new_key_2" : ['subdict1']['subdict2']['old_key_2'],
"new_key_3" : ['subdict1']['subdict3']['old_key_3']
}
然后,对于每个嵌套的dict,我可以用简单的for循环生成一个新的dict对象:
Then, for each nested dict, I could generate a new dict object with a simple for loop:
for key, value in new_dict.items() :
user_dict_1[key] = OldDict[value]
嵌套的dicts非常大,我只需要几个每个字段,否则我可以使用.copy()函数来处理旧的dict。
The nested dicts are very large and I only need a few fields from each, otherwise I could just use the .copy() function to work with the old dicts.
PS-任何帮助重写这个问题,更可读
PS- Any help in rewriting this question to be more readable also appreciated.
推荐答案
您将需要 reduce()
这一个...
You're going to need reduce()
for this one...
attrmap = {
"new_key_1": ('subdict1', 'subdict2', 'old_key_1'),
...
}
print reduce(lambda x, y: x[y], attrmap[somekey], old_object)
这篇关于在python中使用dict键作为不同的dict中的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!