我有这个测试词典:
addressBook = {'a' : {'Name' : 'b', 'Address' : 'c', 'PhoneNo' : '5'}, 'd' : {'Name' : 'e', 'Address' : 'f', 'PhoneNo' : '7'}}
我想遍历addressBook中的每个字典并显示每个值(名称,地址和phoneno)。
我试过这个:
for x in addressBook:
for y in x:
print(y, "\t", end = " ")
但是,这只会打印每个字典的键(即' a'和'')。
如何显示所有值?
答案 0 :(得分:3)
默认情况下,只要迭代字典,python只会迭代字典中的键。
您需要使用iteritems
方法迭代字典中的值,或使用(key, value)
方法迭代存储在该字典中的for x in addressBook.itervalues():
for key, value in x.iteritems():
print((key, value), "\t", end = " ")
对。
请改为尝试:
class PropertyController extends AdminController {
public function langUpdate(Request $request)
{
$result = PropertyRltLang::create($request->all());
return back()->with('resultLangUpdate',$result);
}
}
答案 1 :(得分:3)
我会做这样的事情
for k1,d in addressBook.items:
for k2,v2 in d.items:
print("{} :: {}".format(k2, v2))
但是,如果你想要的只是整齐地打印字典,我建议
import pprint
s = pprint.pformat(addressBook)
print(s)
答案 2 :(得分:1)
迭代字典只能为您提供字典键,而不是值。如果您只想要这些值,请使用:
for x in addressBook.values()
或者,如果您想要键和值,请使用iteritems(),如下所示:
for key,value in addressBook.iteritems():
print key, value
答案 3 :(得分:1)
您的代码问题:
for x in addressBook: # x is key from the addressBook dictionary.
#- x is key and type of x is string.
for y in x: # Now we iterate every character from the string.
print(y, "\t", end = " ") # y character is print
请尝试以下操作:
for i in addressBook:
print "Name:%s\tAddress:%s\tPhone:%s"%(addressBook[i]["Name"], addressBook[i]["Address"], addressBook[i]["PhoneNo"])
Name:b Address:c Phone:5
Name:e Address:f Phone:7