【发布时间】:2019-06-22 18:23:48
【问题描述】:
我有一个 json 文件中的字典列表。
我已经遍历列表和每个字典,以从每个字典中为每个元素获取两个特定的键:值对。
即List[dictionary{i(key_x:value_x, key_y:value_y)}]
我现在的问题是:
如何将这两个新的key:value对放置在一个新的list/dictionary/array/tuple中,代表两个key:value对为原始中的每个列出的元素提取?
要明确:
ORIGINAL_LIST (i.e. with each element being a nested dictionary) =
[{"a":{"blah":"blah",
"key_1":value_a1,
"key_2":value_a2,
"key_3":value_a3,
"key_4":value_a4,
"key_5":value_a5,},
"b":"something_a"},
{"a":{"blah":"blah",
"key_1":value_b1,
"key_2":value_b2,
"key_3":value_b3,
"key_4":value_b4,
"key_5":value_b5,},
"b":"something_b"}]
所以到目前为止我的代码是:
import json
from collections import *
from pprint import pprint
json_file = "/some/path/to/json/file"
with open(json_file) as json_data:
data = json.load(json_data)
json_data.close()
for i in data:
event = dict(i)
event_key_b = event.get('b')
event_key_2 = event.get('key_2')
print(event_key_b)#print value of "b" for each nested dict for 'i'
print(event_key_2)#print value of "key_2" for each nested dict for 'i'
要明确:
FINAL_LIST(i.e. with each element being a nested dictionary) =
[{"b":"something_a", "key_2":value_2},
{"b":"something_b", "key_2":value_2}]
【问题讨论】:
-
你能澄清一下你的
FINAL_LIST,为什么只有key_2在场? -
由于某种原因堆栈删去了字典的第二部分,它应该有另一个嵌套字典 {"b":"something_b", {"key_2":value_2}}]
-
最终列表应该是:[{"b":"something_a", {"key_2":value_2}}, {"b":"something_b", {"key_2":value_2}}]
-
将其添加到问题中
-
我想我理解你的困惑,我用于最终列表的嵌套字典没有意义,我在问题中对其进行了编辑以反映这一点,谢谢
标签: python arrays dictionary tuples