【发布时间】: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