python-3.x 如何更改字典中的所有值/键

rqdpfwrv  于 2023-01-27  发布在  Python
关注(0)|答案(1)|浏览(213)

我不知道该如何恰当地描述它,但这就是我想要实现的:

import yaml
list = {"test1":1,"test2":2,"test3":3}
print(yaml.dump(list, sort_keys=False, default_flow_style=False))

#Output
# test1: 1
# test2: 2
# test3: 3

# Update somehow

print(yaml.dump(list, sort_keys=False, default_flow_style=False))

#Output
# <@test1>: 1
# <@test2>: 2
# <@test3>: 3
4ngedf3f

4ngedf3f1#

使用理解来变换关键帧:

# list is not a list but a dict and don't use builtin names
data = {"test1":1,"test2":2,"test3":3}

# transform your keys
data = {f'<@{k}>': v for k, v in data.items()}

# export your data as usual
print(yaml.dump(data, sort_keys=False, default_flow_style=False)

输出:

<@test1>: 1
<@test2>: 2
<@test3>: 3

相关问题