Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

python - Delete dictionary in embedded list of dictionaries based on index number?

I have an embedded list of dictionaries within a list, e.g.:

mylist = {'mydict': [{'A': 'Letter A','ay':'alpha'},
                     {'B': 'Letter B','bee':'beta'},
                     {'C': 'Letter C','cee':'cat'}]}

How do I delete one of the dictionaries in the list based on it's index number? The key:value pairs within the dictionary may change with each new iteration of the list, so it's necessary to use index number.

For example, if I chose to delete index[1] the list of dicts would result in:

mylist = {'mydict': [{'A': 'Letter A','ay':'alpha'},
                     {'C': 'Letter C','cee':'cat'}]}

Thanks for the help!

question from:https://stackoverflow.com/questions/65648241/delete-dictionary-in-embedded-list-of-dictionaries-based-on-index-number

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

1 Reply

0 votes
by (71.8m points)

Thanks for your well-explained question. The answer is simpler than your details though, your question is the same as "how do I delete from a list by index"

items = [1, 2, 3]
del items[1]
assert items == [1, 3]

It is the same for your question

del my_list["mydict"][1]

Since my_list["mydict"] is your list.

As an aside, the way you describe needing to delete by index makes me think it is not the best method, it also will change the indices, so you may have some larger design level issues.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...