如何使用Python在同一行上打印两个不同的词典?

2024-10-04 01:24:32 发布

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

我有一个问题,我不知道如何在同一行上打印两本词典。你知道吗

我有:

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秒,我需要知道如何以相同的方式直接在线打印两个词典,而不会在代码执行上严重浪费时间。你知道吗


Tags: keyincityforzipdictfantasylist
3条回答

可能是这样?你知道吗

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

如果您想将任意数量的字典(可能,不仅是幻想和真实的)与多个对象类型(可能,不仅是城市和城镇)连接并对齐,您可能会发现pandas很有用:

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 

试试这是:-

Fantasy = {"Gotham":["city", 2000], "Smallville":["town", 30]}
Real = {"London":["city", 1000], "Whitby":["town", 40]}

for i,j in zip(Fantasy,Real):
    print (i,end='')
    print (" ",Fantasy[i][-1],end = '')
    print (" ",j,end='')
    print (" ",Real[j][-1])

相关问题 更多 >