比较和打印两个词典中的值

时间:2015-12-06 07:16:51

标签: python dictionary

我有两个包含词典的Python列表

的List1

[{'domain': 'www.google.com', 'visits': 100, 'sessions': 50}, 
{'domain': 'www.youtube.com', 'visits': 50, 'sessions': 20}]

列表2

[{'domain': 'www.google.com', 'visits': 120, 'sessions': 55}, 
{'domain': 'www.facebook.com', 'visits': 30, 'sessions': 10}]

我想要以下输出

Domain            Visits1  Sessions1   Visits2  Sessions2 
www.google.com    100      50          120      55
www.youtube.com   50       20            
www.facebook.com                       30       10

我正在尝试使用itertools和zip来弄清楚我是否可以自己做,但我被卡住了,任何帮助都会受到赞赏。

1 个答案:

答案 0 :(得分:3)

首先将数据放入dict:

L1 = [{'domain': 'www.google.com', 'visits': 100, 'sessions': 50}, 
      {'domain': 'www.youtube.com', 'visits': 50, 'sessions': 20}]
L2 = [{'domain': 'www.google.com', 'visits': 120, 'sessions': 55}, 
      {'domain': 'www.facebook.com', 'visits': 30, 'sessions': 10}]

res = {}

for counter, item in enumerate([L1, L2], 1):
    for entry in item:
        domain = entry['domain']
        domain_dict = res.setdefault(domain, {})
        domain_dict['Visits{}'.format(counter)] = entry['visits']
        domain_dict['Sessions{}'.format(counter)] = entry['sessions']

结果如下:

>>> res
{'www.facebook.com': {'Sessions2': 10, 'Visits2': 30},
 'www.google.com': {'Sessions1': 50,
  'Sessions2': 55,
  'Visits1': 100,
  'Visits2': 120},
 'www.youtube.com': {'Sessions1': 20, 'Visits1': 50}}

现在打印出来:

longest = max(len(x) for x in res.keys())
header = ['Domain', 'Visits1', 'Sessions1', 'Visits2', 'Sessions2']
print('{:{w}s} '.format(header[0], w=longest), end='')
print(' '.join(header[1:]))
for domain, data in res.items():
    print('{:{w}s}'.format(domain, w=longest), end=' ')
    for head in header[1:]:
        value = data.get(head, 0)
        print('{:{w}d}'.format(value, w=len(head)), end=' ')
    print()

输出:

Domain           Visits1 Sessions1 Visits2 Sessions2
www.youtube.com       50        20       0         0 
www.facebook.com       0         0      30        10 
www.google.com       100        50     120        55 

不喜欢缺失值的零。使用空格:

...

    for head in header[1:]:
        value = str(data.get(head, ''))
        print('{:>{w}s}'.format(value, w=len(head)), end=' ')
    print()

打印:

Domain           Visits1 Sessions1 Visits2 Sessions2
www.youtube.com       50        20                   
www.facebook.com                        30        10 
www.google.com       100        50     120        55