[英]Inserting dict objects from a list with key-value pairs to a new list
我有一个叫做data
的dict
,它有一个名为clubs
key
,它映射到包含dict
对象的list
。 我想将clubs
list
中的每个对象添加到新list
。
我可以遍历list
并创建一个新list
,但是arr
仅包含dict
对象的key
名。 如何将整个dict对象(而不只是键名)添加到新列表中? 基本上我想要clubs
辞典中的清单。
这是我的arr
列表的样子:
['key1', 'key2', 'key1', 'key2', 'key1', 'key2', 'key1', key2]
这是我的实现:
arr = []
for item in data['clubs']:
arr.extend(item)
print (len(arr))
print (arr)
我不明白为什么我只得到字符串(键名),在Objective-c中它会起作用。( data['clubs']
是一个list
, item
是我添加到新list
的list
中的dict
obj叫做arr
。
这是原始(json)数据的外观:
{ "clubs": [
{
"location": "Dallas",
"id": "013325K52",
"type": "bar"
},
{
"location": "Dallas",
"id": "763825X56",
"type": "restaurant"
}
] }
我想要这样的事情:
{
"location": "Dallas",
"id": "013325K52",
"type": "bar"
},
{
"location": "Dallas",
"id": "763825X56",
"type": "restaurant"
}
arr.extend(item)
将尝试将item
解释为一个sequence
,并将该序列中的所有项目添加到arr
。 要添加单个元素,请使用append
。
arr = []
for item in data['clubs']:
arr.append(item)
print(arr)
但是,您可以这样写:
print(list(data['clubs']))
您的JSON已经是键/值对,其中值是python list
。 要将其提取到自己的列表中,只需从键中进行分配:
arr = data['clubs'] # returns the list associated with this key!
如果您需要对列表/字典中的项目进行任何其他处理,则这可能更有用:
arr = [{}]* len(data['clubs'])
for k, v in enumerate(data['clubs']):
arr[k] = v
print(arr)
结果应为:
[
{'type': 'bar',
'location': 'Dallas',
'id': '013325K52'},
{'type': 'restaurant',
'location': 'Dallas',
'id': '763825X56'}
]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.