[英]print keys and values from dictionary
I have a dictionary :我有一本字典:
d = {'A': ['1', '2'],
'B': ['1', '2'],
'C': ['2', '2',],
'D': ['1', '3']}
And I want to write print it like我想把它写成这样
A 1
A 2
B 1
B 2
C 1
C 2
D 1
D 2
Tried to write试着写
for i in d.keys():
for j in d2.values():
print(i,j)
But in gives me ALL combinations not that I need.但是 in 给了我所有不是我需要的组合。
Try iterating the dictionary sorted by key.尝试迭代按键排序的字典。 Then, use each key to access the list of numbers for that key.
然后,使用每个键访问该键的数字列表。
for i in sorted(d):
for j in d[i]:
print(i + ' ' + j)
This prints:这打印:
A 1
A 2
B 1
B 2
C 2
C 2
D 1
D 3
here you go -干得好 -
d = {'A': ['1', '2'],
'B': ['1', '2'],
'C': ['2', '2',],
'D': ['1', '3']}
for (k,v) in d.items():
i=0
while i < len(v):
print(k,v[i])
i= i+1
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.