将特定的字典键添加到列表中(Python 2.6)

Adding specific Dictionary key to a list (Python 2.6)

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

我有一本像这样的字典:

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

我还有另一个字典列表,其中包含许多 ID,例如:

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

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

  }

我需要将这些词典添加到 'children' 列表中。

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

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

可能吧?但可惜它是 2.6,我完全不知道该怎么做。任何想法将不胜感激。

预期输出:

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

    {
    "id": 1004,
    },

    {
    "id": 1008,
    }

]
}

虽然在 Python 2.6 中不支持字典理解,但您仍然可以使用 dict 构造函数。由于看起来您想向列表中添加多个项目,因此 extend 可能比 append.

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