在日常开发中,遇到一个需求,就是一个列表,里面存放多个字典,类似于这样
a = [{'station': '0435', 'value': '1'}, {'station': '0435', 'value': '0'}, {'station': '0435', 'value': '1'},
{'station': '0435', 'value': '0'}, {'station': '0436', 'value': '0'}, {'station': '0436', 'value': '0'},
{'station': '0436', 'value': '0'}, {'station': '0436', 'value': '0'}]
需求是将station的value取出作为新的key,将相同station value的其它value取出放入一个列表中,舍弃key,类似于这样
{'0435': ['1', '0', '1', '0'], '0436': ['0', '0', '0', '0']}
实现方法
a = [{'station': '0435', 'value': '1'}, {'station': '0435', 'value': '0'}, {'station': '0435', 'value': '1'},
{'station': '0435', 'value': '0'}, {'station': '0436', 'value': '0'}, {'station': '0436', 'value': '0'},
{'station': '0436', 'value': '0'}, {'station': '0436', 'value': '0'}]
# 创建新的字典
d = dict()
for i in a:
d[i['station']] = d.get(i['station'], [])
d[i['station']].append(i['value'])
print(d)
最终实现。
有更好实现方式的同学可以留言,共同沟通一下
打赏
如果您觉得不错,请打赏作者吧~