Home > Enterprise >  How to check if layered dictionary key exists and if it is not how do I create it on the fly?
How to check if layered dictionary key exists and if it is not how do I create it on the fly?

Time:08-16

So I wrote this code to dynamically create dictionary entries from variables if the keys provided in those variables do not exist in the dictionary:

example_dict = {'jack' : {'long' : {'color' : 'red'}}}

name = 'jane'
hair = 'short'
color = 'color'
shade = 'blue'

if name not in example_dict:
    example_dict[name] = {hair : {color : shade}}
else:
    if hair not in example_dict[name]:
        example_dict[name][hair] = {color : shade}
    else:
        if color not in example_dict[name][hair]:
            example_dict[name][hair][color] = shade
        else:
            example_dict[name][hair][color] = shade

print(example_dict)

This is working, but I feel it is clumsy and can be done in a more simple fashion, perhaps even as a one-liner. Would you be able to suggest a better perhaps faster alternative, please?

CodePudding user response:

There doesn't seem to be a reason for these checks, you're just checking if the data is in the dict and if not then adding it. Therefore there is no reason for all the checks.

example_dict = {'jack': {'long': {'color': 'red'}}}

name = 'jane'
hair = 'short'
color = 'color'
shade = 'blue'

# to keep with your first check
example_dict[name] = {hair: {color: shade}}
# or this if the first if doesn't matter
example_dict = {name: {hair: {color: shade}}

CodePudding user response:

Instead of having the keys in separate variables, you could put them in a list and iterate over them as you drill down into your dictionary.

def assign_nested_dict(d, keys):
    if len(keys) < 2: raise ValueError("keys must have at least two elements")

    # Loop over all but last two elements of keys
    for k in keys[:-2]:
        if k not in d or not isinstance(d[k], dict):
            # If this key doesn't exist, or it isn't a dict, create it
            d[k] = dict()  
        # Drill down, so next iteration can access the dict at the current key
        d = d[k]

    # Set the key-value pair for the leaf dictionary
    d[keys[-2]] = keys[-1]

Since this function modifies the dict in place, you don't need to return from it.

example_dict = {'jack': {'long': {'color': 'red'}}}


assign_nested_dict(example_dict, ['jane', 'short', 'color', 'blue'])
print(example_dict)
# {'jack': {'long': {'color': 'red'}}, 'jane': {'short': {'color': 'blue'}}}

assign_nested_dict(example_dict, ['jane', 'long', 'color', 'black'])
print(example_dict)
# {'jack': {'long': {'color': 'red'}},
# 'jane': {'short': {'color': 'blue'}, 'long': {'color': 'black'}}}
  • Related