Answer to Question #345383 in Python for Roggers

Question #345383

consider the invert_dict function from Section 11.5 of your textbook. 

# From Section 11.5 of: 

# Downey, A. (2015). Think Python: How to think like a computer scientist. Needham, Massachusetts: Green Tree Press. 


def invert_dict(d):

   inverse = dict()

   for key in d:

      val = d[key]

     if val not in inverse:

        inverse[val] = [key]

     else:

        inverse[val].append(key)

   return inverse 


Modify this function so that it can invert your dictionary. In particular, the function will need to turn each of the list items into separate keys in the inverted dictionary. 

Run your modified invert_dict function on your dictionary. Print the original dictionary and the inverted one. 

Include your Python program and the output in your Learning Journal submission. 



1
Expert's answer
2022-05-27T09:39:34-0400
def invert_dict(d):
    inverse = dict()
    for key in d:
        val = d[key]
        if val not in inverse:
            inverse[val] = [key]
        else:
            inverse[val].append(key)
    return inverse


def invert_dict_mod(d):
    inverse = dict()
    key: str
    for key in d:
        val = d[key]
        # Conditional operator "if 5.0 in 5" is equal to True
        if val not in inverse:
            inverse[val] = key
        else:
            inverse[str(val) + '_' + str(key)] = key
    return inverse


def invert_dict_mod_2(d):
    """
    Invert original dictionary with {key: val, ...} pairs in such a way
    that inverted dictionary would consist of {(val, key): key, ...} pairs,
    where now a key is a tuple (val, key) and a value is a key of the original
    dictionary

    :param d: original dictionary
    :return: inverted dictionary
    """
    inverse = dict()
    key: str
    for key in d:
        val = d[key]
        inverse[(val, key)] = key
    return inverse


dict1 = {"a": 1, "b": 2, "c": 2, "d": 3, "e": 4, "f": 5, "g": 5, "h": 5, "i": 6}
# dict1 = {"a": "c", "b": 2, "c": 2, "d": 3, "e": 4, "f": 5, "g": 5, "h": 5, "i": 6, 2: 5.0, 3: 5.1}

print("original dictionary:\n", dict1)
dict2 = invert_dict(dict1)
print("inverted dictionary:\n", dict2)
dict3 = invert_dict_mod(dict1)
print("modified inverted dictionary:\n", dict3)
dict4 = invert_dict_mod_2(dict1)
print("modified inverted dictionary:\n", dict4)

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS