gpt4 book ai didi

python - 将Python字典键对转换为字符串

转载 作者:行者123 更新时间:2023-12-01 00:34:37 25 4
gpt4 key购买 nike

我是Python新手,我有一个Python字典,如下所示

{"details":[{"name":"akhil","account":"ABCD"},{"name":"rahul","account":"GCOD"},{"name":"rakesh","account":"ABCD"}]}

需要将此字典转换为Python字符串,如下所示。还有一点,这本词典是动态的,所以它应该有点通用。

ABCD -
akhil
rakesh
GCOD -
rahul

提前致谢,如有任何帮助,我们将不胜感激。

最佳答案

使用简单的迭代。

data = {"details":[{"name":"akhil","account":"ABCD"},{"name":"rahul","account":"GCOD"},{"name":"rakesh","account":"ABCD"}]}

result = {}
#Group name by account!.
for i in data["details"]:
result.setdefault(i["account"], []).append(i["name"])

for k, v in result.items():
print("{} -\n{}".format(k, "\n".join(v)))

输出:

ABCD -
akhil
rakesh
GCOD -
rahul

关于python - 将Python字典键对转换为字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57901030/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com