[英]How do I print elements of a list contained in a dictionary using a for loop
I have a dictionary: 我有一本字典:
FFA = {'House': ['0.511', '0.374', 10], 'Chair': ['0.704', '0.381', 10], 'Shoe': ['0.922', '0.465', 10], 'Bottle': ['0.764', '0.348', 10], 'Face': ['1.084', '0.373', 10]}
I want to print certain elements in a for loop: 我想在for循环中打印某些元素:
print "ROI", "Cope", "Mean", "Stddev", "Nsamples"
for k in FFA:
print "FFA", k, elem[0], elem[1], elem[2]
That's my output: 那是我的输出:
ROI Cope Mean Stddev Nsamples
FFA House 1.084 0.373 10
FFA Chair 1.084 0.373 10
FFA Shoe 1.084 0.373 10
FFA Bottle 1.084 0.373 10
FFA Face 1.084 0.373 10
However, my code is so wrong I can't find a way of iterating over all the keys in the dic so the right values are printed out. 但是,我的代码太错了,我找不到在dic中所有键上进行迭代的方法,因此无法正确打印出值。
I want my output to be: 我希望我的输出是:
ROI Cope Mean Stddev Nsamples
FFA House 0.511 0.374 10
FFA Chair 0.704 0.381 10
FFA Shoe 0.922 0.465 10
FFA Bottle 0.764 0.348 10
FFA Face 1.084 0.373 10
You were close: 您接近:
print "ROI", "Cope", "Mean", "Stddev", "Nsamples"
for k in FFA:
elem = FFA[k]
print "FFA", k, elem[0], elem[1], elem[2]
or directly: 或直接:
print "ROI", "Cope", "Mean", "Stddev", "Nsamples"
for k in FFA:
print "FFA", k, FFA[k][0], FFA[k][1], FFA[k][2]
Use items()
to iterate over the keys and the values. 使用
items()
遍历键和值。 Since you have multiple values, iterate over the values using the nested for loop over multiple values. 由于您具有多个值,因此可以使用嵌套的for循环遍历多个值来遍历这些值。 For python 2.x it will be
print "FFA", k, values,
对于python 2.x,它将
print "FFA", k, values,
print "ROI", "Cope", "Mean", "Stddev", "Nsamples" # Header
for k, v in FFA.items():
# print ("FFA", k, end=" ") # For python 3.x
print "FFA", k,
for values in v:
print values,
# print (values, end=" ") # For python 3.x
print # To get to print to the new line
# print () # For python 3.x
ROI Cope Mean Stddev Nsamples
FFA House 0.511 0.374 10
FFA Chair 0.704 0.381 10
FFA Shoe 0.922 0.465 10
FFA Bottle 0.764 0.348 10
FFA Face 1.084 0.373 10
You already loop over the keys, now you simply need to loop over the elements of the values: 您已经遍历了键,现在只需要遍历值的元素:
FFA = {'House': ['0.511', '0.374', 10],
'Chair': ['0.704', '0.381', 10],
'Shoe': ['0.922', '0.465', 10],
'Bottle': ['0.764', '0.348', 10],
'Face': ['1.084', '0.373', 10]}
print "ROI", "Cope", "Mean", "Stddev", "Nsamples"
for k in FFA: # loop over keys in dict
print "FFA", k, # , at end == no newline
for elem in FFA[k]: # loop over values in list of key
print elem, # , at end == no newline
print # now a newline
Output: 输出:
ROI Cope Mean Stddev Nsamples
FFA House 0.511 0.374 10
FFA Chair 0.704 0.381 10
FFA Shoe 0.922 0.465 10
FFA Bottle 0.764 0.348 10
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.