|
dict = {'name':'ngy','age':23,'height':180}
1. 最简单的方式:
print(dict)
结果:
{'name': ngy, 'age': 23, 'height': 180}
dict是无序的,若想有序打印,将其转化为list排序,
按key值排序,然后可以用PrettyTable输出:
list = sorted(dict.items(), key = lambda d:d[0])
table = PrettyTable(["key","value"])
table.align["key"] = "l"
table.padding_width = 1
for tup in list:
table.add_row([tup[0], tup[1]])
print(table)
按value值排序:
list = sorted(dict.items(), key = lambda d:d[1])
2. 逐个打印key:
for key in dict.keys():
print('key = {}'.format(key))
结果:
key = name
key = age
key = height
3. 逐个打印value:
for value in dict.values():
print('value = {}'.format(value))
结果:
value = ngy
value = 23
value = 180
4. 逐个打印key:value:
for key,value in dict.items():
print('{key}:{value}'.format(key = key, value = value))
结果:
name:ngy
age:23
height:180
|
|