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

标签 python python-2.7 dictionary

假设我有这 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 执行的附加方法组合 d1d23

我应该如何处理b)

如果d123_new不适合以我想要的表格格式打印数据,请告诉我。

最佳答案

这可以解决问题:

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

关于Python:嵌套字典:获取字符串(键+值)作为值,然后与键交换,组合字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38113585/

相关文章:

python - 递归 - Python

python - 监听 Web 应用程序的输出

尝试在 __getattr__ 中返回默认值时 Python pickle 崩溃

python - 使用键和值列表到字典

python - Plotly 3D 绘图注释

python - 在 Windows 中使用信号中断 python multiprocessing.Process

python - Bottle :全局变量 'request' 未定义

python - 如何在 tkinter ~ python 中放置在网格中的两个小部件之间添加空间?

python - PySpark df to dict : one column as key, 另一个作为值

python - 当其中一个元素是 Python 字典时,向 MySQL 表中插入一行