[英]Python dictionary format change splitting keys
我怎么能从这种格式的字典中获得 go
{'A.B': 7, 'C.D': 5, 'A.D': 34}
对此:
{'A': {'B':7, D:34} , 'C': {'D': 5} }
键 'AB' 的含义是 i go 从 A 到 B 并且它的值意味着 7 次,所以我想要做的是改变这种格式,以便我的字典键是我 go 的位置,它的值是一个字典目的地(一个或多个)和每个目的地的时间。
我已经尝试了几件事,但现在事情还没有解决。
我曾尝试将 for 与新字典一起使用,但它会覆盖我的键。
使用默认字典:
d = {'A.B': 7, 'C.D': 5, 'A.D': 34}
from collections import defaultdict
formatted_d = defaultdict(dict)
for k, v in d.items():
top_key, bottom_key = k.split('.')
formatted_d[top_key][bottom_key] = v
没有默认字典:
formatted_d = {}
for k, v in d.items():
top_key, bottom_key = k.split('.')
if top_key not in formatted_d:
formatted_d[top_key] = {}
formatted_d[top_key][bottom_key] = v
collections.defaultdict
:
from collections import defaultdict
dct = {'A.B': 7, 'C.D': 5, 'A.D': 34}
new_dict = defaultdict(dict)
for key, value in dct.items():
root, descendant = key.split(".")
new_dict[root][descendant] = value
print(new_dict)
这产生
defaultdict(<class 'dict'>, {'A': {'B': 7, 'D': 34}, 'C': {'D': 5}})
快速方法:
d = {'A.B': 7, 'C.D': 5, 'A.D': 34}
dicts_init = {key.split('.')[0]: {} for key, value in d.items()}
for key, value in d.items():
root_k, val = key.split(".")
dicts_init[root_k][val] = value
print(dicts_init)
输出:
{'A': {'B': 7, 'D': 34}, 'C': {'D': 5}}
d = {'A.B': 7, 'C.D': 5, 'A.D': 34}
result = {}
for key in d:
current, destination = key.split('.')
times = d.get(key)
if current not in result.keys():
result[current] = {destination: int(times)}
else:
result[current][destination] = int(times)
print(result)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.