[英]How do I append a dictionary as another value to an existing dictionary key
[英]How do I append to an existing array list in a dictionary?
我有这本字典:
{ "hex" : [] }
我希望能够运行一个方法,我可以在其中输入一个将附加到该列表中的值,但是,我想保存该列表的 memory 以便如果我要运行该方法两次,我会得到两个条目。
因此例如方法(1),方法(2)将返回:
{ "hex" : [1,2] }
这是我的代码:
def getMultiHex(file, getHexCode):
hexDict = {}
with open(file, 'r') as datafile:
data = json.load(datafile)
for index, element in enumerate(data):
hex_iter = iter(element.values())
hex_code = next(hex_iter)
if getHexCode == hex_code:
elem = element['hex']
hexDict['hex'] = []
hexDict['hex'].append(elem)
with open('Multihex.json', 'w') as w:
databox = json.dump(hexDict, w)
return hexDict`
现在这有效,但每次我运行该方法输入不同的值时,字典都会被覆盖。 我知道每次执行该方法时我都会初始化一个新字典,但是我有什么解决方法?
提前致谢
如果每次添加元素时都重新创建列表(在代码中: hexDict['hex'] = []
),旧值显然会被覆盖。 您可以预先定义字典值,例如
data = dict(some_key=[])
for x in new_data:
data["some_key"].append(x)
或者您可以只使用defaultdict
:
from collections import defaultdict
data = defaultdict(list)
for x in new_data:
data["some_key"].append(x) # the list will be created if the key doesn't exist
如果您想通过多次调用外部 function 将数据添加到同一个字典,您可以在第一次调用之前创建字典并将其传递给所有调用,每次都附加数据:
def add_data(data, new_data):
for x in new_data:
data["some_key"].append(x)
data = defaultdict(list)
add_data(data, [1, 2])
add_data(data, [3, 4])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.