防止 OrderedDict 在迭代期间将单个字符串值拆分为字符

prevent OrderedDict from splitting single string value into characters during iteration

我想制作一个 OrderedDict,每个键都有一个字符串,每个值都有一个字符串列表。

from collections import OrderedDict

# Compare a dict with an OrderedDict
someDict = dict(a = ["foo","bar"], b = ["baz"])
someOrderedDict = OrderedDict([("a",("foo","bar")),("b",("baz"))])

我需要迭代这个字典来访问键和值。在普通字典中,这很简单:

for k,v in someDict.items():
    for eachv in v:
        print("do something with key = " + k + " and value = " + eachv)
# returns the desired output:
# do something with key = a and value = foo
# do something with key = a and value = bar
# do something with key = b and value = baz

(如果这可以在理解中完成,请赐教——我无法弄清楚如何在不丢失密钥的情况下完成。)

当我在 OrderedDict 上尝试这个时,我得到:

for k,v in someOrderedDict.items():
    for eachv in v:
        print("do something with key = " + k + " and value = " + eachv) 
# results in undesirable splitting of value "baz" into ["b","a","z"]:
# do something with key = a and value = foo
# do something with key = a and value = bar
# do something with key = b and value = b
# do something with key = b and value = a
# do something with key = b and value = z

我做错了什么?

这是因为您将字符串 (("baz")) 分配给 b 键,而不是元组 (("baz",)) 或字符串列表。

而不是

someOrderedDict = OrderedDict([("a",("foo","bar")),("b",("baz"))])

尝试

someOrderedDict = OrderedDict([("a",("foo","bar")),("b",("baz",))])

(注意新逗号。)

您可以在 "baz" 之后添加一个 ,,这样它就可以在 for 循环期间被解释为一个元组而不是单个 str

someOrderedDict = OrderedDict([("a",("foo","bar")),("b",("baz",))])

然后,迭代可以很好地获取元组的单个元素 baz:

for k,v in someOrderedDict.items():
    for eachv in v:
        print("do something with key = " + k + " and value = " + eachv)
do something with key = b and value = baz
do something with key = a and value = foo
do something with key = a and value = bar

同样可以通过将值包装在 []:

中来实现
[("a", ["foo","bar"]),("b", ["baz"])]

更好,如果您已经有可用的字典,只需使用 [=22] 在 someOrderedDict 中展开(解压)字典 someDict =]语法:

someOrderedDict = OrderedDict(**someDict)

效果同样好,看起来更加紧凑和干净