2013-10-08 82 views
-5

我有兩個集合一個是列表,另一個是不同長度像這些打印列表並排

list = [1,2,3,4,5,6] 
dict = {'one':1,'two':2} 

我怎麼能打印出來作爲字典...

List  Dictionary 
1  one:1 
2  two:2 
3 
4 
5 
6 

燦任何人都可以幫助我?

+1

字典是無序的,所以你不能保證將線條比賽。 – interjay

+2

你應該寫下你所嘗試過的,而不只是要求解決方案。 – Henrik

+0

Down選民,你可以在這裏留下評論... –

回答

1

用自己的名字覆蓋內置名字是個壞習慣。 'list'和'dict'都是Python中的內置類型,所以你不想把這些名稱分配給它們。

還要記住,詞典是Python中的無序數據結構。如果你想命令,你必須使用該記住哪些命令你插入的元素在OrderedDict

from collections import OrderedDict 
l = [1,2,3,4,5,6] 
d = {'one':1,'two':2} 
od = OrderedDict(sorted(d.items(), key=lambda x: x[1])) 
print 'List'.ljust(9) + 'Dictionary' 
rows = zip(l, od.items()) 
# Print elements matched with zip 
for r in rows: 
    print str(r[0]).ljust(9) + repr(r[1])[1:-1].replace(', ', ':').replace(
                    '\'', '') 
# Print any leftover unmatched elements in your list 
for i in xrange(len(rows), len(l)): 
    print l[i] 

輸出:

List  Dictionary 
1  one:1 
2  two:2 
3 
4 
5 
6 
+0

我不介意abt dircinary物品Shashank的訂購,我只是想打印它們。你的例子很好。非常感謝。 –

+0

嗨shahank,你可以請清除一個永無止境的疑惑..如果字典比列表更大。我的意思是字典的長度超過了列表的長度? –