且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在python字典中的键具有多个值?

更新时间:2023-01-17 20:02:42

您不能在具有相同键的字典中包含多个项.您应该做的是将值设置为list.像这样-

You can't have multiple items in a dictionary with the same key. What you should do is make the value a list. Like this -

d = dict()
d["flow"] = ["flow"]
d["flow"].append("wolf")

如果这是您要执行的操作,则可能要使用

If that is what you want to do, then you might want to use defaultdict. Then you can do

from collections import defaultdict
d = defaultdict(list)
d["flow"].append("flow")
d["flow"].append("wolf")