![](/img/trans.png)
[英]Python looping over dictionary to substitute keys with the values from another dictionary
[英]Looping over a dictionary of lists and output keys and values
我有一個類似以下示例中的Python腳本:
dictionary = {
'key1': ['value1', 'value2', 'value3', 'value4', 'value5', 'value6', 'value7', 'value8', 'value9', 'value10'],
'key2': ['value1', 'value2', 'value3', 'value4', 'value5', 'value6', 'value7', 'value8', 'value9', 'value10']
}
for key, value in dictionary.items():
i = 0
for i in range (0, 10):
print (key, "|", value[i])
i = i+1
我希望它能打印出類似以下結果的內容:
key1|value1
key1|value2
key1|value3
(and so on for all the keys in the input)
IndexError Traceback(最近一次調用最后一次)在()189 i = 0190中,范圍(0,10)中的i:-> 191 print(鍵,“ |”,value [i])192 i = i + 1
IndexError:列表索引超出范圍
我知道我可能會缺少一些東西:感謝那些有時間發表評論的人!
希望您發現字典中缺少'
引號。 in
運算符中使用以避免索引問題。
for key, value in dictionary.items():
for val in value:
print (key, "|", val)
第一個問題的根源是您在列表中缺少value2之前的'。
其次,代碼的i = 0
和i = i+1
部分是多余的,因為i
每次都是由for循環分配的。 我不會遍歷一個范圍,而是遍歷您的值列表:
dictionary = {
'key1': ['value1', 'value2', 'value3', 'value4', 'value5', 'value6', 'value7', 'value8', 'value9', 'value10'],
'key2': ['value1', 'value2', 'value3', 'value4', 'value5', 'value6', 'value7', 'value8', 'value9', 'value10']
}
for key, values in dictionary.items():
for value in values:
print(key, "|", value)
由於這將適用於任意長度列表:)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.