按其中一个键的值拆分字典 [英] Splitting dict by value of one of the keys

查看:53
本文介绍了按其中一个键的值拆分字典的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含相同长度(但类型不同)数据的字典,例如:

I've got a dictionary with data of the same length (but different types), something like:

data = {
    "id": [1,1,2,2,1,2,1,2], 
    "info": ["info1","info2","info3","info4","info5","info6","info7","info8"],       
    "number": [1,2,3,4,5,6,7,8]
}

现在我想通过 id 将它分成两部分,保留各自的 infonumber.也就是说,有两个字典 data1data2.

Now I'd like to split it in two by id, keeping the respective info and number. That is, to have two dicts data1 and data2.

注意:这只是一个示例,字典中有多个键,我想避免使用键名,而是遍历所有键名.

Note: this is merely a sample, there are multiple keys in the dict and I would want to avoid using the key names, but rather loop through all of them.

Pythonic 的做法是什么?

What is a Pythonic way of doing it?

推荐答案

with comprehension lists :

with comprehension lists :

data1 = [ data["info"][idx] for idx, x in enumerate(data["id"]) if x == 1 ]
#data1 = ['info1', 'info2', 'info5', 'info7']

如果您想恢复所有密钥:

If you want to recover all the keys :

data1 = [ { key : data[key][idx] for key in data.keys() }  for idx, x in enu
merate(data["id"]) if x == 1 ]
>>> data1
[{'info': 'info1', 'id': 1, 'number': 1}, {'info': 'info2', 'id': 1, 'number': 2
}, {'info': 'info5', 'id': 1, 'number': 5}, {'info': 'info7', 'id': 1, 'number':
 7}]

这篇关于按其中一个键的值拆分字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆