[Coding test] 11. isinstance()

whitehousechef·2025년 8월 27일

isinstance

So I wanted to check if an object is a dictionary. But I didnt know how

for that we can use isinstance(object,type)

print(isinstance({"a": 1}, dict))   # True
print(isinstance([1, 2, 3], dict)) # False
print(isinstance(42, dict))        # False

example

We wanna merge 2 nested dictionaries and if the nested val is primitive, we override it. Else if it is dictionary, we need to override some values.

iterative:

def merge_dicts_nested_for(d1, d2):
    result = d1.copy()
    
    # Outer loop over keys of d2
    for key in d2:
        if key in result and isinstance(result[key], dict) and isinstance(d2[key], dict):
            # Nested loop over keys of the nested dictionary
            for nested_key in d2[key]:
                result[key][nested_key] = d2[key][nested_key]  # overwrite or add
        else:
            result[key] = d2[key]  # overwrite or add top-level key
    return result

# Example
dict1 = {'a': 1, 'b': {'x': 10, 'y': 20}}
dict2 = {'b': {'y': 30, 'z': 40}, 'c': 3}

merged = merge_dicts_nested_for(dict1, dict2)
print(merged)
# Output: {'a': 1, 'b': {'x': 10, 'y': 30, 'z': 40}, 'c': 3}

recursive:

def merge_dicts(d1, d2):
    result = d1.copy()  # start with all keys/values from d1
    for key, value in d2.items():
        if key in result and isinstance(result[key], dict) and isinstance(value, dict):
            # RECURSIVE CALL happens here
            result[key] = merge_dicts(result[key], value)
        else:
            result[key] = value  # overwrite or add new key
    return result

0개의 댓글