Python 字典格式更改拆分键
Python dictionary format change splitting keys
我怎么能从这种格式的字典中走出来
{'A.B': 7, 'C.D': 5, 'A.D': 34}
对此:
{'A': {'B':7, D:34} , 'C': {'D': 5} }
键'A.B'的意思是我从A到B,它的值意味着7次,所以我想做的是改变这种格式,这样我的字典键就是我从哪里去它的价值是一本字典,包含他的目的地(一个或多个)和每个目的地的时间。
我已经尝试了几件事,但目前还没有成功。
我尝试将 for 与新词典一起使用,但它覆盖了我的键。
快速方法:
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}
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}
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)
我怎么能从这种格式的字典中走出来
{'A.B': 7, 'C.D': 5, 'A.D': 34}
对此:
{'A': {'B':7, D:34} , 'C': {'D': 5} }
键'A.B'的意思是我从A到B,它的值意味着7次,所以我想做的是改变这种格式,这样我的字典键就是我从哪里去它的价值是一本字典,包含他的目的地(一个或多个)和每个目的地的时间。
我已经尝试了几件事,但目前还没有成功。
我尝试将 for 与新词典一起使用,但它覆盖了我的键。
快速方法:
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}
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}
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)