python 字典键值重复_python - 通过重复字典键值拆分python字典列表

假设我有一个字典列表:foo = [

{'host': 'localhost', 'db_name': 'test', 'table': 'partners'},

{'host': 'localhost', 'db_name': 'test', 'table': 'users'},

{'host': 'localhost', 'db_name': 'test', 'table': 'sales'},

{'host': 'localhost', 'db_name': 'new', 'table': 'partners'},

{'host': 'localhost', 'db_name': 'new', 'table': 'users'},

{'host': 'localhost', 'db_name': 'new', 'table': 'sales'},

]

如何将这个列表分割成单独的列表(或列表),其中“主机”和“dByNeX”是相同的?

例如:

list1 = [

{'host': 'localhost', 'db_name': 'test', 'table': 'partners'},

{'host': 'localhost', 'db_name': 'test', 'table': 'users'},

{'host': 'localhost', 'db_name': 'test', 'table': 'sales'},

]

list2 = [

{'host': 'localhost', 'db_name': 'new', 'table': 'partners'},

{'host': 'localhost', 'db_name': 'new', 'table': 'users'},

{'host': 'localhost', 'db_name': 'new', 'table': 'sales'},

]

最佳答案

>>> from collections import defaultdict

>>> dd = defaultdict(list)

>>> foo = [

{'host': 'localhost', 'db_name': 'test', 'table': 'partners'},

{'host': 'localhost', 'db_name': 'test', 'table': 'users'},

{'host': 'localhost', 'db_name': 'test', 'table': 'sales'},

{'host': 'localhost', 'db_name': 'new', 'table': 'partners'},

{'host': 'localhost', 'db_name': 'new', 'table': 'users'},

{'host': 'localhost', 'db_name': 'new', 'table': 'sales'},

]

>>> for d in foo:

dd[(d['host'], d['db_name'])].append(d)

列表列表是字典的值

>>> dd.values()

[[{'table': 'partners', 'host': 'localhost', 'db_name': 'new'}, {'table': 'users', 'host': 'localhost', 'db_name': 'new'}, {'table': 'sales', 'host': 'localhost', 'db_name': 'new'}], [{'table': 'partners', 'host': 'localhost', 'db_name': 'test'}, {'table': 'users', 'host': 'localhost', 'db_name': 'test'}, {'table': 'sales', 'host': 'localhost', 'db_name': 'test'}]]

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值