将字典键传递给新字典

时间:2012-12-23 17:10:37

标签: python dictionary for-loop key

为什么这段代码不起作用?它返回key3的键错误。 adict有key3,它与我在空字典中添加键的方式没有什么不同,除了我在循环中彼此之间传递它们。如何将一个字典中的键和值传递给具有相同主键的新字典?

adict = {'key1':{'a':.078, 'b':1000, 'c':100},
                          'key2':{'a':.0645, 'b':10, 'c':5},
                          'key3':{'a':.0871, 'b':250, 'c':45},
                          'key4':{'a':.0842, 'b':200, 'c':37},
                          'key5':{'a':.054, 'b':409, 'c':82},
                          'key6':{'a':.055, 'b':350, 'c':60}}

another_dict = {}
for k in adict:
    another_dict[k]['transferred'] = adict[k]['b']


>>>   Traceback (most recent call last):
      File "C:\Python27\test.py", line 26, in <module>
        another_dict[k]['transferred'] = adict[k]['b']
      KeyError: 'key3'

5 个答案:

答案 0 :(得分:2)

在访问之前,您必须在another_dict[k]创建一个新词典:

adict = {'key1':{'a':.078, 'b':1000, 'c':100},
                      'key2':{'a':.0645, 'b':10, 'c':5},
                      'key3':{'a':.0871, 'b':250, 'c':45},
                      'key4':{'a':.0842, 'b':200, 'c':37},
                      'key5':{'a':.054, 'b':409, 'c':82},
                      'key6':{'a':.055, 'b':350, 'c':60}}

another_dict = {}
for k in adict:
    if k not in another_dict:
        another_dict[k] = {}
    another_dict[k]['transferred'] = adict[k]['b']

答案 1 :(得分:2)

如果我理解正确,使用dict理解起来相当简单:

>>> pprint({k:{'transferred':v['b']}  for k, v in adict.iteritems()})
{'key1': {'transferred': 1000},
 'key2': {'transferred': 10},
 'key3': {'transferred': 250},
 'key4': {'transferred': 200},
 'key5': {'transferred': 409},
 'key6': {'transferred': 350}}

你也可以做一个便利功能,只保留某些子键(如果它们的名字相同)

>>> from operator import itemgetter
>>> def dict_with_subkeys(odict, *keys):
    return {k:dict(zip(keys, itemgetter(*keys)(odict[k]))) for k in odict}

>>> pprint(dict_with_subkeys(adict, 'a', 'c'))
{'key1': {'a': 0.078, 'c': 100},
 'key2': {'a': 0.0645, 'c': 5},
 'key3': {'a': 0.0871, 'c': 45},
 'key4': {'a': 0.0842, 'c': 37},
 'key5': {'a': 0.054, 'c': 82},
 'key6': {'a': 0.055, 'c': 60}}

答案 2 :(得分:1)

使用another_dict[k]['transferred'],您正在尝试访问尚未创建的'transferred'字典的key k密钥。

您可以在此处使用defaultdict: -

from collections import defaultdict
another_dict = defaultdict(dict)

修改后的代码: -

>>> from collections import defaultdict
>>> adict = {'key1':{'a':.078, 'b':1000, 'c':100},
...                           'key2':{'a':.0645, 'b':10, 'c':5},
...                           'key3':{'a':.0871, 'b':250, 'c':45},
...                           'key4':{'a':.0842, 'b':200, 'c':37},
...                           'key5':{'a':.054, 'b':409, 'c':82},
...                           'key6':{'a':.055, 'b':350, 'c':60}}
... 
... another_dict = defaultdict(dict)
... for k in adict:
...     another_dict[k]['transferred'] = adict[k]['b']

>>> another_dict
5: defaultdict(<type 'dict'>, {'key3': {'transferred': 250}, 
                           'key2': {'transferred': 10}, 
                           'key1': {'transferred': 1000}, 
                           'key6': {'transferred': 350}, 
                           'key5': {'transferred': 409}, 
                           'key4': {'transferred': 200}})

答案 3 :(得分:1)

问题是another_dict[k]实际上还不存在,而您正尝试对甚至未初始化的内容执行another_dict[k]['transferred']。所以你需要先将它初始化:

In [35]: adict = {'key1':{'a':.078, 'b':1000, 'c':100},
                          'key2':{'a':.0645, 'b':10, 'c':5},
                          'key3':{'a':.0871, 'b':250, 'c':45},
                          'key4':{'a':.0842, 'b':200, 'c':37},
                          'key5':{'a':.054, 'b':409, 'c':82},
                          'key6':{'a':.055, 'b':350, 'c':60}}

In [36]: another_dict={}

In [37]: for k in adict:
    another_dict[k]={}                          #initialize another_dict[k]
    another_dict[k]['transferred']=adict[k]['b']

In [38]: another_dict
Out[38]: 
{'key1': {'transferred': 1000},
 'key2': {'transferred': 10},
 'key3': {'transferred': 250},
 'key4': {'transferred': 200},
 'key5': {'transferred': 409},
 'key6': {'transferred': 350}}

答案 4 :(得分:0)

谢谢@Ashwini我理解你的观点。和@Jon一样。

随着我对Python和(“词典理解”?)的改进,我找到的另一个解决方案是:

another_dict = {k:{'b':adict[k]['b']} for k in adict}