Python 需要字典魔法

Python dictionary magic needed

我有这两个 Python 词典,其中包含关联的位置和数量。

A: {'Pompano Beach': ['13'], ' Miami': ['18'], ' W. Palm Beach': ['18']}
B:  {'Atlanta': ['25'], 'Las Vegas': ['50+']}

我需要在 html table 中打印出来。我目前正在使用带有 jinja2 模板的烧瓶。

我希望我的结果为:

C: {'Pompano Beach': ['13', '0'], ' Miami': ['18', '0'], ' W. Palm Beach': ['18', '0'], 'Atlanta': ['0','25'], 'Las Vegas': ['0', '50+']}

其中每个列表值中的0索引是A的数量,1索引是B的数量。 另外,如果B中不存在该城市,则添加一个0。如果A中不存在,则在其相应索引中添加一个0。

我不确定是否有更简单的解决方案,但我认为这是我需要的,以便使用 jinja2 模板保持我的样式。

您可以在使用默认值为 ['0'].get 时使用字典理解:

C = {k: A.get(k, ['0']) + B.get(k, ['0']) for k in list(A) + list(B)}
print(C)

产出

{'Pompano Beach': ['13', '0'], ' Miami': ['18', '0'], ' W. Palm Beach': ['18', '0'], 
 'Atlanta': ['0', '25'], 'Las Vegas': ['0', '50+']}

您可以获得相同的输出,同时避免创建 2 个额外的列表

C = {k: A.get(k, ['0']) + B.get(k, ['0']) for k in A.keys() | B.keys()}