如何在python字典中的键具有多个值? [英] How to have multiple values for a key in a python dictionary?

查看:180
本文介绍了如何在python字典中的键具有多个值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到的情况是,同一键可能具有与之关联的不同字符串.

I have a case where the same key could have different strings associated with it.

例如flow和wolf都具有相同的字符,如果我将它们排序并用作字典中的键,我想将原始字符串作为值.

e.g. flow and wolf both have the same characters, if I sort them and use them as keys in a dictionary, I want to put the original strings as values.

我在python字典中尝试过:

I tried in a python dict as:

d = {}

d["flow"] = flow
d["flow"] = wolf

但是只有一个与键相关联的值.

but there is only one value associated with the key.

我尝试了d["flow"].append("wolf"),但这也行不通.

I tried d["flow"].append("wolf") but that also doesn't work.

如何使这种情况与Python字典配合使用?

How to get this scenario working with Python dicts?

推荐答案

您不能在具有相同键的字典中包含多个项.您应该做的是将值设置为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")

这篇关于如何在python字典中的键具有多个值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆