我有一个问题我不知道如何在同一行上打印两个字典。
我有:
Fantasy = {"Gotham":[city, 2000], "Smallville":[town, 40], "Nuketown":[town,60]}
Real = {"London":[city, 1500], "Whitby":[town, 40], "Liverpool":[city, 1000]}
我试过这个(通过):
listFantasy = dictList(Fantasy)
listReal = dictList(Real)
def dictList (dict):
list = []
for key, value in dict_.iteritems(): # Create list form dict
temp = [key,value]
lista_finale.append(temp)
return list
for list1, list2 in zip(listFantasy, listReal):
print list1[0]
for listValue1, listValue2 in zip(list1[1:],list2[1:]):
listValue1.sort(key = lambda x: x[1], reverse = True)
listValue2.sort(key = lambda x: x[1], reverse = True)
for value1, value2 in zip(listValue1, listValue2):
print " \n %-10s \t %-10s" % (valore1[0], valore1[1]),"\t\t\t\t %-10s \t %-10s" % (valore2[0], valore2[1])
输出:
Gotham London
city 2000 city 1500
NukeTow Liverpool
town 60 city 1000
Smallville Whitby
town 40 town 40
但是这个解决方案非常慢,需要大约30秒,我需要知道如何以相同的方式在线直接打印两个词典,而不会在代码执行上浪费时间。
答案 0 :(得分:4)
可能是这样的吗?
>>> Fantasy = {'Gotham':['city', 2000], 'Smallville':['town', 30]}
>>> Real = {'London':['city', 1000], 'Whitby':['town', 40]}
>>> print '{:15}\t\t{:15}'.format('Fantasy','Real')
>>> for c1,c2 in zip(sorted(Fantasy),sorted(Real)):
print '{:10}{:5}\t\t{:10}{:5}'.format(c1, Fantasy[c1][1], c2,Real[c2][1])
Fantasy Real
Gotham 2000 London 1000
Smallville 30 Whitby 40
答案 1 :(得分:1)
答案 2 :(得分:1)
试试这个: -
{{1}}
答案 3 :(得分:1)
如果你想加入和对齐任意数量的词典(可能,不仅是幻想和真实),有多种对象类型(可能,不仅仅是城市和城镇),你可能会发现pandas
有用:< / p>
Fantasy = {'Gotham':['city', 2000], 'Smallville':['town', 30]}
Real = {'London':['city', 1000], 'Whitby':['town', 40]}
# You have to code 'Fantasy' and 'Real' as strings, for Python to interpret and print them
dicts = {'Fantasy': Fantasy, 'Real': Real}
import pandas as pd
frames = []
for key, value in dicts.items():
# Create a small table from each dict
frame = pd.DataFrame(value, index=['type', 'size']).T.reset_index().set_index('type')
# Add an extra column name (e.g. 'Fantasy')
frame.columns = pd.MultiIndex.from_arrays([[key]*2, frame.columns])
frames.append(frame)
print(pd.concat(frames, axis=1))
此代码打印的内容比您想要的多一点,但我认为这些额外信息很有用,必须明确显示:
Fantasy Real
index size index size
type
city Gotham 2000 London 1000
town Smallville 30 Whitby 40