[英]Nested dictionary. Merging common keys and appending values to list. 0 value isn't appending. Code inside
代码: https://pastebin.com/GJn74YX5
我有一个带有数据结构的嵌套字典:
foo[count] [字符串变量] = value
foo = { 0 : { "a": 2, "b": 5, "c": 6},
1 : { "a": 3, "b": 8, "d": 9},
2 : { "b": 5, "d": 9, "c": 3}}
我想采用这些 dicts 的共同值并将共同值组合到适当的键变量中。 也许在新的字典中可行。 如果公共变量不适用于该特定计数,它将添加一个 0 。 新字典中的所有值都应该是相同的长度。 看起来像这样:
{ "a": [2, 3, 0], "b": [5, 8, 5], "c":[6, 0, 3], "d": [0,9,9] }
我的做法:
创建 newdict 一个 defaultdict(list) 以便我可以检查密钥是否存在以及 append 到列表中,如上所示。 这将是我想要的最终命令
newdict = defaultdict(list)
创建以下 for 循环到 append 到新字典:
for count in foo.keys(): for variable in foo[count].keys(): if variable in foo[count].keys(): newdict[variable].append(foo[count].get(variable)) elif variable not in foo[count].keys(): newdict[variable].append(0) else: newdict[variable] = foo[count].get(variable)
我的问题:
Output:
{ "a": [2, 3], "b": [5, 8, 5], "c":[6, 3], "d": [9,9] }
我花了几个小时似乎无法解释为什么没有附加 0。 任何帮助表示赞赏。 先感谢您!
问题在于这些代码行:
for count in foo.keys():
for variable in foo[count].keys():
您正在按照它们出现的顺序浏览这些键,例如,如果“d”只出现在与第二个键相关的字典中,那么它在第一个 position 中将没有任何值。 该问题可以通过首先生成随后可能出现的所有键的列表来解决,以下代码有效,但是可以对其进行优化。
from collections import defaultdict
foo = { 0 : { "a": 2, "b": 5, "c": 6},
1 : { "a": 3, "b": 8, "d": 9},
2 : { "b": 5, "d": 9, "c": 3} }
key_list = []
for count in foo.keys():
for variable in foo[count].keys():
if variable not in key_list:
key_list.append(variable)
newdict = defaultdict(list)
for count in foo.keys():
for variable in key_list:
if variable in foo[count].keys():
newdict[variable].append(foo[count].get(variable))
elif variable not in foo[count].keys():
newdict[variable].append(0)
else:
newdict[variable] = foo[count].get(variable)
newdict
这是一种可能的替代方法:
from collections import defaultdict
# directly prepare the correct list size
newdict = defaultdict(lambda: [0]*len(foo))
for count in foo:
for v in foo[count]:
newdict[v][count] = foo[count][v]
Output:
>>> dict(newdict)
{'a': [2, 3, 0],
'b': [5, 8, 5],
'c': [6, 0, 3],
'd': [0, 9, 9]}
如果字典索引不是 0,1,2... 您可以使用for i count in enumerate(foo)
并且i
将是子列表的索引。
希望,这也可能有所帮助:
all_keys = []
newdict = {}
# identify all unique keys
for count in foo.keys():
all_keys.append(list(foo[count].keys()))
all_keys = np.unique(all_keys)
# prepare final dictionary
for i in all_keys:
newdict[i] = []
# collect data
for count in foo.keys():
check_key = set(list(all_keys)).difference(list(foo[count].keys()))
for variable in foo[count].keys():
newdict[variable].append(foo[count][variable])
if check_key:
for key in check_key:
newdict[key].append(0)
newdict
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.