簡體   English   中英

將特定的Dictionary鍵添加到列表(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"

  }

我需要將這些詞典添加到“兒童”列表中。

如果是2.7,我可能會做:

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

可能嗎? 但是可惜它是2.6,我絕對不知道該怎么做。 任何想法都會非常感激。

預期產量:

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

    {
    "id": 1004,
    },

    {
    "id": 1008,
    }

]
}

盡管dict理解在Python 2.6中不可用,但是您仍然可以使用dict構造函數。 由於您似乎要向列表添加多個項目,所以extend可能比append更適合。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM