【问题标题】:Append nested list from one dictionary to a nested list of another dictionary?将嵌套列表从一个字典附加到另一个字典的嵌套列表?
【发布时间】:2021-06-08 15:02:28
【问题描述】:

我有两本词典:

a = {'name': 'Bob', 'values': ['abcd']}
b = {'name': 'Jack', 'values': ['efg']}

期望的输出:

b = {'name': 'Jack', 'values': ['abcd','efg']}

当前代码:(不需要的输出)

b['values'].append(a['values'])

print(b)
>>>{'name': 'Jack', 'values': ['abcd', ['efg']]}

【问题讨论】:

    标签: python list dictionary append


    【解决方案1】:

    不要追加,你应该添加元素:

    b['values']+=a['values']
    

    【讨论】:

      【解决方案2】:

      你也可以试试listsextend方法如:

      b['values'].extend(a['values'])
      
      >>> b
      {'name': 'Jack', 'values': ['efg', 'abcd']}
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2020-06-01
        • 2020-12-30
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-10-07
        • 1970-01-01
        相关资源
        最近更新 更多