在python中使用dict键作为不同字典中的值

时间:2012-07-13 16:39:23

标签: python dictionary

我想创建一个“转换器”类型的dict,它会将不同dicts中的键值分配给我创建的dict中的键。我遇到的问题是我不能创建一个表示嵌套的dict键的值,而不必将其转换为字符串或其他数据类型,当我尝试使用字符串作为嵌套字典的索引时,我收到索引错误。理想情况下,我的dict看起来像这样:

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对象:

for key, value in new_dict.items() :
    user_dict_1[key] = OldDict[value]

嵌套的dicts非常大,我只需要几个字段,否则我可以使用.copy()函数来处理旧的dicts。

PS-任何有助于重写此问题以获得更多可读性的帮助也值得赞赏。

2 个答案:

答案 0 :(得分:4)

你需要reduce()这个......

attrmap = {
  "new_key_1": ('subdict1', 'subdict2', 'old_key_1'),
   ...
}

print reduce(lambda x, y: x[y], attrmap[somekey], old_object)

答案 1 :(得分:0)

你在说这样的话吗?

from pprint import pprint as pp
subdict1 = {'subdict1_item1':1, 'subdict1_item2':2}
subdict2 = {'subdict2_item1':3, 'subdict2_item2':4}
subdict3 = {'subdict3_item1': 5, 'subdict3_item1':6}
olddict = {
    'old_key_1': [subdict1, subdict2],
    'old_key_2': [subdict1, subdict2],
    'old_key_3': [subdict1, subdict3],
    }

newdict = {
    'new_key_1': olddict['old_key_1'].append('old_key_1'),
    'new_key_2': olddict['old_key_2'].append('old_key_2'),
    'new_key_3': olddict['old_key_3'].append('old_key_3'),
    }

或者

newdict = {
    'new_key_1': 'old_key_1',
    'new_key_2': 'old_key_2',
    'new_key_3': 'old_key_3',
    }
def getnew(newkey, newdict, olddict):
    if newkey in newdict:
        oldkey = newdict[newkey]
        if oldkey in olddict:
            preitem = olddict[ oldkey ] # returns a list with two items
            item = []
            item.append([preitem[0]]) # makes subdict1 wrapped in a list
            item.append([preitem[1]]) # makes subdict2/3 wrapped in a list
            item.append([oldkey])
            return item
        else:
            raise KeyError('newdict has no matching olddict key')

结果:

pp( getnew('new_key_1', newdict, olddict) )
print 
pp( getnew('new_key_2', newdict, olddict) )
print
pp( getnew('new_key_3', newdict, olddict) )
[[{'subdict1_item1': 1, 'subdict1_item2': 2}],
 [{'subdict2_item1': 3, 'subdict2_item2': 4}],
 ['old_key_1']]

[[{'subdict1_item1': 1, 'subdict1_item2': 2}],
 [{'subdict2_item1': 3, 'subdict2_item2': 4}],
 ['old_key_2']]

[[{'subdict1_item1': 1, 'subdict1_item2': 2}],
 [{'subdict3_item1': 6}],
 ['old_key_3']]