Subseting dictionaries in Python

Question:

I would like to get d3 from d2 and d1. That said, I would lke the keys that d1 and d2 have in common and take the 0th element of criterion and the 1st element of other, as opposed to the index itself. The result d3 should contain any left over keys that were not in d1 as well as the selected values. Thank you.

d1 = {'criterion': 0, 'other':1, 'n_estimators': 240}

d2 = {'criterion': ["gini", "entropy", "log_loss"], 'other': ["sqrt", "log2"]}

d3 = {'criterion': "gini", 'other':"entropy", 'n_estimators': 240}
Asked By: helpmeplease

||

Answers:

Just loop over d1, getting values from d2 where available, and keeping the d1 value otherwise:

d3 = {}
for k, v in d1.items():
    if k in d2:
        d3[k] = d2[k][v]
    else:
        d3[k] = v

A perhaps overly concise version of this can be written as a dictcomp:

d3 = {k: d2[k][v] if k in d2 else v for k, v in d1.items()}
Answered By: ShadowRanger

I’m guessing at what you actually want here, and am providing a suggestion for better design. d2 is a dictionary that maps a category number to a string, I think. So let’s give it a more descriptive name. I assume you will do this for many dicts, so you should make a function to do so.


def dictmaker(d_in):
    category_dict = {'criterion': ["gini", "entropy", "log_loss"], 'other': ["sqrt", "log2"]}
    d_new = {}
    for k, v in d_in.items():  # iter thru input dict
        if k in category_dict:  # if key is a category-type key
            v = category_dict[k][v]  # get the category string and set to value
        d_new[k] = v
    return d_new
    
print(dictmaker({'criterion': 0, 'other':1, 'n_estimators': 240}))

Answered By: likethevegetable
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.