Skip to main content
 首页 » 编程设计

元组列表的 Python 字典。打印元组中的元素列表

2024年11月01日12freeliver54

我在 python 中有一个字典,例如:

{1: [('type', 'USB'), ('ipaddress', '192.168.1.1'), ('hostname', 'hello'), ('realname', 'world')], 2: [('type', 'Stereo'), ('ipaddress', '192.168.1.2'), ('hostname', 'hi'), ('realname', 'mum')]} 

我将如何以主机名的关键顺序(1、2 等)打印列表,这样输出将是:

hello 
hi 

谢谢

请您参考如下方法:

这是将内部对列表转换为字典的解决方案。这样做的好处是无论 hostname 条目的位置如何,它都可以工作:

>>> for order, pairs in sorted(d.items()): 
        print dict(pairs)['hostname'] 
 
 
hello 
hi