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

时间:2016-06-30 14:25:13

标签: python python-3.x dictionary ordereddictionary

我想为每个键创建一个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

我做错了什么?

2 个答案:

答案 0 :(得分:3)

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

而不是

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

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

(注意新的逗号。)

答案 1 :(得分:2)

您可以在,之后添加"baz",以便在str循环期间将其解释为元组而不是单个for

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"])]

更好,如果您已有字典,只需使用someDict语法扩展(解包)someOrderedDict中的字典**:< / p>

someOrderedDict = OrderedDict(**someDict)

它同样有效,看起来更紧凑和干净