Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
3.6k views
in Technique[技术] by (71.8m points)

python 3.x - Verify Method Of Finding Index of List of Dicts with Nested Dict Structure

Starting with an empty list, I have code that iterates through database documents and I'm going to be creating a data structure something like this for each unique subject across the database:

var = {"subject": "A", "data" : [{'type1' : {'sub_type1' : {'_id1' : '123'}, {'_id2' : '345'}}, {'sub_type2' : {'_id3' : '456'}, {'_id4' : '567'}}}, {'type2' : {'sub_type1' : {'_id5' : '123'}, {'_id6' : '345'}},{'sub_type2' : {'_id7' : '456'}, {'_id8' : '567'}}, ...}}

While I'm iterating, I create the "type" and "sub_type" dicts if they are not there from the data in the documents. Not all the "type" and "sub_type" keys are common across subjects.

The trouble is that while iterating, I have trouble finding the index of the "type" dicts that I need so I can populate this dict with the rest of the data. I know I should have a different data structure but for arguments sake, let's say that I can't.

I came up with making a flattened list with this list comprehension:

[key for dic in var["data"] for key in list(dic.keys())]

which should give me this list: ['type1', 'type2', ...]. Then I index this list by passing in the "type" and I think this should correspond to the index of the bigger list in var['data'].

I'm afraid that the index between the list comprehension and var['data'] won't match up but I think this code will work because I create the list in var['data'] so it should maintain and match it's order when I make the list comprehension.

Am I wrong about this?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
等待大神解答

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...