Python:嵌套字典:获取字符串(键+值)作为值,然后与键交换,组合字典

2024-04-23 23:13:12 发布

您现在位置:Python中文网/ 问答频道 /正文

假设我有3本字典:

d1 = {'Ben': {'Skill': 'true', 'Magic': 'false'}, 'Tom': {'Skill': 'true', 'Magic': 'true'}}
d2 = {'Ben': {'Strength': 'wo_mana', 'Int': 'wi_mana', 'Speed': 'wo_mana'}, 'Tom': {'Int': 'wi_mana', 'Agility': 'wo_mana'}}
d3 = {'Ben': {'Strength': '1.10', 'Int': '1.20', 'Speed': '1.50'}, 'Tom': {'Int': '1.40', 'Agility': '1.60'}}

我想得到这样的东西:

d123_new = {'Ben': {'wo_mana': ['Strength = 1.10', 'Speed = 1.50'], 'wi_mana': ['Int = 1.20'], 'Skill': 'true', 'Magic': 'false'},
'Tom': {'wi_mana': ['Int = 1.40'], 'wo_mana': ['Agility = 1.60'], 'Skill': 'true', 'Magic': 'true'}}

我认为用这样的表格格式打印比较容易(可能是我错了):

Name Skill Magic wo_mana          wi_mana
Ben  true  false Strength = 1.10  Int = 1.20
                 Speed = 1.50
Tom  true  true  Agility = 1.60   Int = 1.40

所以我想我必须首先组合/附加d1d2,这是我的代码和结果(d12):

import itertools, collections

def update(d, u):
    for k, v in u.iteritems():
        if isinstance(v, collections.Mapping):
            r = update(d.get(k, {}), v)
            d[k] = r
        else:
            d[k] = u[k]
    return d
d12 = update(d2, d1)
print(d12)

d12 = {'Ben': {'Skill': 'true', 'Magic': 'false', 'Strength': 'wo_mana', 'Int': 'wi_mana', 'Speed': 'wo_mana'},
       'Tom': {'Skill': 'true', 'Magic': 'true', 'Int': 'wi_mana', 'Agility': 'wo_mana'}}

然后,我想得到d3_new,它是这样的:

d3_new = {'Ben': ['Strength = 1.10', 'Int = 1.20', 'Speed = 1.50'],
          'Tom': ['Int = 1.40', 'Agility = 1.60']}

我的代码和此部分的结果(d3_new):

d3_new = {}
for i in d3;
    a = ''.join(['%s = %s' %(k,v) for k,v in d3[i].iteritems()])
    d3_new[i] = list()
    d3_new[i].append(a)
print(d3_new)

d3_new = {'Ben': ['Int = 1.20Strength = 1.10Speed = 1.50'],
          'Tom': ['Int = 1.40Agility = 1.60']}

显然,我所期望的输出和d3_new得到的输出是不同的。我该怎么解决这个问题?你知道吗

在获得d3_new所需的输出之后,下一步是什么?或者我应该首先遵循以下步骤:

a)将d3改为d3_new

b)将d2d3_new合并到

d23 = {'Ben': {'wo_mana': ['Strength = 1.10', 'Speed = 1.50'], 'wi_mana': ['Int = 1.20']},
       'Tom': {'wi_mana': ['Int = 1.40'], 'wo_mana': ['Agility = 1.60']}}

c)使用我为d12所做的append方法组合d1d23

我该怎么办b)?你知道吗

如果d123_new不适合以我想要的表格格式打印数据,请通知我。你知道吗


Tags: truenewmagicstrengthskillintd3speed
2条回答

以下是如何做到这一点:

d1 = {'Ben': {'Skill': 'true', 'Magic': 'false'}, 
      'Tom': {'Skill': 'true', 'Magic': 'true'}}
d2 = {'Ben': {'Strength': 'wo_mana', 'Int': 'wi_mana', 'Speed': 'wo_mana'},   
      'Tom': {'Int': 'wi_mana', 'Agility': 'wo_mana'}}
d3 = {'Ben': {'Strength': '1.10', 'Int': '1.20', 'Speed': '1.50'}, 
      'Tom': {'Int': '1.40', 'Agility': '1.60'}}

d123_new = {} # create an empty dict

for key in d1: # run over first dict and get the keys containing names

    try:   # Case of Skill

        d = {
             key:{ # we know the key and Agility case 
                  d2[key]['Agility']:['Agility='+d3[key]['Agility']],
                  d2[key]['Int']: ['Int='+d3[key]['Agility']],
                  'Skill':d1[key]['Skill'],'Magic':d1[key]['Magic']
             }
       }

   except KeyError: # case of Strength

       d = {
             key:{ # no Agility - Strength
                  d2[key]['Strength']:['Strength='+d3[key]['Strength'],
                  'Speed='+d3[key]['Speed']],
                  d2[key]['Int']: ['Int='+d3[key]['Strength']],
                 'Skill':d1[key]['Skill'],'Magic':d1[key]['Magic']
             }
        }

    d123_new.update(d)

print d123_new # output the result

这可以做到:

d4 = {}
for k, v in d2.items():
  d4[k] = {}
  for k2, v2 in v.items():
    try:
      if v2 not in d4[k]:
        d4[k][v2] = [k2 + ' = ' + d3[k][k2]]
      else:
        d4[k][v2].append(k2 + ' = ' + d3[k][k2])
    except KeyError:
        # this means k2 is a typo in d2; skip
        assert k in d3 # be sure that a missing name isn't causing the KeyError
        # you only need to use pass when you don't have any other operations in the scope

for k, v in d1.items():
  for k2, v2 in v.items():
    d4[k][k2] = v2

print(d4 == d123_new)
# -> True

相关问题 更多 >