2013-11-22 131 views
2

我有一个字典中像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等)的列表的表示,主机名,以便输出将是:

hello 
hi 

感谢

+2

你说的按键的顺序是什么意思? Python中的字典没有订购 – wnnmaw

回答

1

下面是内部对列表转换为字典中的溶液。这具有优势在于,它将无论工作主机入口的位置:

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


hello 
hi 
1

这似乎做到这一点:

>>> 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 

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

(I假设(“主机名”,字符串)元组始终是在相同的位置)

+0

//,它在Mac OSX El Capitan的Python 2.7.10中产生预期的输出。 –