我想为每个键创建一个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
我做错了什么?
答案 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)
它同样有效,看起来更紧凑和干净。