【问题标题】:How to merge a dict into nested dict in python with particular format?如何将字典合并到具有特定格式的python中的嵌套字典中?
【发布时间】:2018-05-18 15:16:09
【问题描述】:

我有一本字典:

digit = { 'one' : 1, 'two' : 2, 'three' : 3, 'four' : 4, 'five' : 5 }

我希望新的嵌套字典是这样的:

new_dict = [{'eng':'one','math': 1}
            {'eng':'two','math': 2}
            {'eng':'three','math': 3}
            {'eng':'four','math': 4}
            {'eng':'five','math': 5}
           ]

我试过了:

digit = { 'one' : 1, 'two' : 2, 'three' : 3, 'four' : 4, 'five' : 5 }
new_dict={'eng':'','math':''}

for nest_key,nest_val in new_dict.items():
    for (key,value),(k,v) in nest_val.items(), digit.items():
        if nest_val['eng'] == '':
            nest_val.update({k:v})  
        nest_val.append({k:v})

print(new_dict)

给出这个错误:

  for (key,value),(k,v) in nest_val.items(), digit.items():  
AttributeError: 'str' object has no attribute 'items'

【问题讨论】:

  • 为什么生活必须如此复杂?看起来new_dict = [{'eng' : k, 'math' : v} for k, v in digit.items()] 运作良好。
  • nest_val 实际上是一个字符串值,没有items() 方法。
  • @coldspeed 对,应该简单地想到。不过感谢您的回复。
  • @Kasramvd 好的,我对here 提到的字典感到困惑。不过谢谢。
  • @coldspeed 答案不断变化,这意味着有时'eng' 成为关键,有时'math'! ?

标签: python python-3.x dictionary nested


【解决方案1】:

正如我在 cmets 中提到的,nest_val 实际上是一个字符串值,没有items() 方法。除此之外,您不必创建另一个字典并通过这样的多个循环对其进行更新。相反,您可以通过一个循环的项目来创建您想要的字典。

lst = []
for name, val in digit.items():
    lst.append({'eng': name,'math': val})

并且以更 Pythonic 的方式,您可以只使用列表推导来拒绝在每次迭代时附加到列表。

lst = [{'eng': name,'math': val} for name, val in digit.items()]

【讨论】:

  • 另一种语法,如果您有大量键,则更有用:[dict(zip(('eng', 'math'), vals)) for vals in digit.items()]
  • @jpp 也许如果你能让它全部功能化(特别是内置函数),它会更像 Python :)。
  • 感谢“pythonic”代码。这真的很有帮助! @Kasramvd。
  • 这么多键会不会有问题? @jpp
  • @Rex5 欢迎。如果可行,您可以接受答案。
猜你喜欢
  • 2018-05-31
  • 1970-01-01
  • 1970-01-01
  • 2021-07-23
  • 2020-11-28
  • 1970-01-01
  • 2022-01-19
  • 1970-01-01
  • 2019-05-16
相关资源
最近更新 更多