元组列表的Python dict。从元组打印元素列表

2024-06-26 17:54:32 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一本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等)打印列表,以便输出:

^{pr2}$

谢谢


Tags: hello列表world字典顺序typehihostname
2条回答

这似乎可以做到:

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

>>> for i in sorted(d.keys()):
    ...     print d[i][2][1]
    ... 
    hello
    hi

您基本上要做的是挑选字典键,对它们进行排序,然后使用它们按顺序从dict打印主机名元组。在

(我假设('hostname',string)元组总是在同一位置)

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

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


hello
hi

相关问题 更多 >