Home > Enterprise >  python filter nested dictionary keys of second nested dict key with function rule IN ONE LINER
python filter nested dictionary keys of second nested dict key with function rule IN ONE LINER

Time:11-02

I have a dictionary in this form:

example ={'2020_01': {'PM0001': 1088, 'CA00006': 33, 'X00002': 125, 'J00009': 119, 'A0000S': 524},
 '2020_02': {'F00067': 3, 'P00001': 1104, 'X00002': 98, 'J0009': 36, 'A0000S': 539},
 '2020_03': {'P00001': 1200, 'Z78800': 45,'X00000': 84,'NK0000': 4,'A0000S': 577,'V000000':11}}

I would like to extract a second dict including only values in the second dictionary nested which keys comply with a certain rule. this rule is given by a function.

def rule(string):
    # this is an hipythetical rule which in reality is way more complicated.
    if string.startswith("P") or string.startswith("X"):
        if string[1] == "0":
            return True
    return False

Using for loops I am able to perform the operation as follows:

new_dict={}
for date,ussage in example.items():
    new_sub_dict = {key:value for key,value in ussage.items() if rule(key)==True}
    new_dict[date] = new_sub_dict
new_dict

The question is if it is possible to rewrite that with one liner.

CodePudding user response:

Try:

new_dict = {
    k: {
        kk: vv
        for kk, vv in v.items()
        if kk.startswith(("P", "X")) and kk[1] == "0"
    }
    for k, v in example.items()
}

print(new_dict)

Prints:

{'2020_01': {'X00002': 125}, '2020_02': {'P00001': 1104, 'X00002': 98}, '2020_03': {'P00001': 1200, 'X00000': 84}}

EDIT: Thanks @KellyBundy to shorten the if-condition.

CodePudding user response:

try

new_dict={date:{key:value for key,value in example[date].items() if rule(key)} for date in example.keys()
  • Related