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
88 views
in Technique[技术] by (71.8m points)

python - How to make key in dictionary to be the key of the dictionary

Is it possible to take the value from a key value pair of a dictionary, and make that the key to the entire dictionary?

In case if what I'm asking is unclear,

I have a list of dictionaries, where the dictionaries look like this:

[{'HOUSE NAME': '1A', 'White Bread loaf large': 1, 'Brown Bread loaf large': 1,
  'Skimmed Milk Pint': 1, 'Cheddar Cheese Medium 300g': 1}, ...]

and this is what I want to change it to:

[1A : {'White Bread loaf large': 1, 'Brown Bread loaf large': 1,
       'Skimmed Milk Pint': 1, 'Cheddar Cheese Medium 300g': 1}, ...]

I'm new to python, and I haven't made an attempt because I really can't think where to start, and I can't seem to find anything online.

question from:https://stackoverflow.com/questions/66054597/how-to-make-key-in-dictionary-to-be-the-key-of-the-dictionary

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

1 Reply

0 votes
by (71.8m points)

Like this:

old_dict = {'HOUSE NAME': '1A', 'White Bread loaf large': 1, 'Brown Bread loaf large': 1, 'Skimmed Milk Pint': 1, 'Cheddar Cheese Medium 300g': 1}
new_dict = {old_dict.pop('HOUSE NAME'): old_dict}

If you have a list of such dictionaries, then just place this inside a loop

new_dict = {}
for old_dict in old_list_of_dicts:
    new_dict[old_dict.pop('HOUSE NAME')]: old_dict

EDIT: Explanation added

Why does this work? dict.pop(key) does two things. Firstly, it returns the value of the dictionary attached to key. Secondly, it removes that entry from the dictionary. As both of these are things asked for in this question, it makes sense to use this function. It's also faster than looping over every entry when creating a new dictionary as in some other answers [note: I haven't tested this explicitly)]. It should be noted however that this modifies the existing dictionary. If this is not desirable, you can either copy the previous old dictionaries or use one of the other answers provided


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

...