我有一本有几个键和值的字典。我希望能够逐行打印特定的键。
my_dictionary = {'vendor': 'Maker', 'hostname': 'PC1',
'os_version': 'OSv1', 'uptime': 7260,
'serial_number': '9NJFB4', 'model': 'Iv2', 'fqdn': 'PC1.lab.local'}
例如,我希望能够打印:
fqdn: PC1.lab.local
serial_number: 9NJFB4
model: Iv2
uptime: 7260
答案 0 :(得分:1)
使用python字典项功能
for (key, value) in my_dictionary.items():
print('{key}: {value}'.format(key=key, value=value)
答案 1 :(得分:0)
您可能正在寻找pprint
import pprint
pp = pprint.PrettyPrinter(width=41, compact=True)
filtered_keys = ['fqdn','serial_number','uptime']
pp.pprint({k:v for k,v in my_dictionary.items() if k in filtered_keys})
#
{'fqdn': 'PC1.lab.local',
'serial_number': '9NJFB4',
'uptime': 7260}
答案 2 :(得分:0)
您可以对dict进行一次简单的迭代,并打印密钥(如果密钥存在于所需的密钥中)。
my_dictionary = {'vendor': 'Maker', 'hostname': 'PC1',
'os_version': 'OSv1', 'uptime': 7260,
'serial_number': '9NJFB4', 'model': 'Iv2', 'fqdn': 'PC1.lab.local'}
needed_keys = ['fqdn', 'serial_number', 'model', 'uptime']
for key, val in my_dictionary.items():
if key in needed_keys:
print(f'{key} : {val}')
# Output
uptime : 7260
serial_number : 9NJFB4
model : Iv2
fqdn : PC1.lab.local
如果python版本低于3.6,并且不支持f字符串,请在format
中使用以下代码来打印键值
my_dictionary = {'vendor': 'Maker', 'hostname': 'PC1',
'os_version': 'OSv1', 'uptime': 7260,
'serial_number': '9NJFB4', 'model': 'Iv2', 'fqdn': 'PC1.lab.local'}
needed_keys = ['fqdn', 'serial_number', 'model', 'uptime']
for key, val in my_dictionary.items():
if key in needed_keys:
print('{key} : {val}'.format(key=key, val=val))