我在Python中有一个字典,如下所示:
dicts = [{'uid':'12345', 'markets':'['UK', 'US']'},
{'uid':'55644', 'markets':'['IN', 'SG', 'IE']'}]
我真正需要的是为“市场”列表中的每个项目制作的任何字典的副本,用于dicts列表中的每个字典。这应该是这样的:
dicts = [{'uid':'12345', 'markets':'['UK']'},
{'uid':'12345', 'markets':'['US']'},
{'uid':'55644', 'markets':'['IN']'},
{'uid':'55644', 'markets':'['IE']'},
{'uid':'55644', 'markets':'['SG']'}]
任何人都可以帮助我理解Python中解决此问题的最佳方法吗?
答案 0 :(得分:2)
以下代码将创建一个词典列表:
dicts = [{'uid':'12345', 'markets':['UK', 'US']},
{'uid':'55644', 'markets':['IN', 'SG', 'IE']}]
def flatten(lists):
res = []
for d in lists:
for market in d['markets']:
res.append({'uid': d['uid'], 'markets': [market]})
return res
print flatten(dicts)
# [{'markets': ['UK'], 'uid': '12345'}, {'markets': ['US'], 'uid': '12345'},
# {'markets': ['IN'], 'uid': '55644'}, {'markets': ['SG'], 'uid': '55644'},
# {'markets': ['IE'], 'uid': '55644'}]
代码将遍历原始列表中的字典。对于每个字典,代码将遍历市场,并且对于每个市场,它将向结果列表添加新字典。除print
外,代码在Python 2和Python 3上都有效。
答案 1 :(得分:0)
你可以(python 3)尝试:
Map<String, Integer> counts = new HashMap<String, Integer>();