【问题标题】:Adding specific Dictionary key to a list (Python 2.6)将特定的字典键添加到列表(Python 2.6)
【发布时间】:2016-07-31 00:03:45
【问题描述】:

您好,我已经为这个问题苦苦挣扎了一段时间。

我有一本像这样的字典:

dict1  =  {
    'Name': 'ID Numbers', 
    'children': []
    }

我还有一个包含多个 ID 的字典列表,例如:

list1 = [
  {
    "id": 1004,
    "othervalue": "blah blah"

  },
  {
    "id": 1008,
    "othervalue": "blah blah"

  }

我需要将这些词典添加到“儿童”列表中。

如果是 2.7,我可能会这样做:

for x in dict1:
  x['children'].append(IDs from list1)

可能吗?但唉,它是 2.6,我完全不知道该怎么做。任何想法都会非常感激。

预期输出:

dict1  =  {
    'Name': 'ID Numbers', 
    'children': [

    {
    "id": 1004,
    },

    {
    "id": 1008,
    }

]
}

【问题讨论】:

  • for x in mydict3: x['children'].extend(list2) ?它实际上会将这些词典添加到“儿童”列表中
  • 首先-抱歉-我更新了代码,我在 list2 中有许多其他键,所以我需要遍历它们。而且该代码似乎无论如何都不起作用? TypeError: string indices must be integers, not str
  • 目前还不清楚您的预期输出是什么。你的list1 是dict。 list2 是字典列表。 mydict3 甚至没有被声明。你能告诉我们minimal reproducible example吗?
  • 我不明白append 的事情。 append 的行为在 Python 2.7 中是否被修改过?
  • 对不起,我在复制数据时不得不更改数据并犯了一些错误。我也提供了预期的输出。基本上,我只是希望能够从list1 中获取 ID 并将它们放入子列表中

标签: python list dictionary python-2.6


【解决方案1】:

尽管 Python 2.6 中不提供 dict 推导式,但您仍然可以使用 dict 构造函数。由于看起来您想将多个项目添加到列表中,extend 可能比append 更适合。

dict1['children'].extend(dict([('id', d['id'])]) for d in list1)

【讨论】:

  • 谢谢你,这工作得很好。为一开始的错误解释道歉!
猜你喜欢
  • 1970-01-01
  • 2023-03-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-09-28
  • 1970-01-01
  • 1970-01-01
  • 2014-03-07
相关资源
最近更新 更多