向列表添加特定字典键(Python2.6)

2024-05-16 00:42:06 发布

您现在位置:Python中文网/ 问答频道 /正文

嗨,我已经为这个问题挣扎了一段时间了。你知道吗

我有一本字典,像:

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,
    }

]
}

Tags: nameinid列表for字典儿童blah
1条回答
网友
1楼 · 发布于 2024-05-16 00:42:06

尽管dict理解在python2.6中不可用,但仍然可以使用^{}构造函数。因为看起来您想将多个项目添加到列表中,extend可能比append更合适。你知道吗

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

相关问题 更多 >