python - Splitting dict by value of one of the keys -


i've got dictionary data of same length (but different types), 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] } 

now i'd split in 2 id, keeping respective info , number. is, have 2 dicts data1 , data2.

note: merely sample, there multiple keys in dict , want avoid using key names, rather loop through of them.

what pythonic way of doing it?

with comprehension lists :

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

if want recover keys :

data1 = [ { key : data[key][idx] key in data.keys() }  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}] 

Comments

Popular posts from this blog

node.js - Bad Request - node js ajax post -

Why does Ruby on Rails generate add a blank line to the end of a file? -

keyboard - Smiles and long press feature in Android -