I am currently trying to figure out how to inverse a dictionary, but for some reason the inversed dictionary is cutting out the last key:value pair. The value has 2 items in it instead of one, which is the only difference between the other key:value pairs. With my current code, it inverses the first 3 names and numbers, but the last one doesn't even show up in the inverse. How would I inverse all four values in the dictionary?
contacts = {
"John A": "858 900 1001",
"Jillian": "858 900 1002",
"Ron": "858 900 1003",
"Miranda": { "mobile": "858 900 1004", "home": "555 1284" }
}
sorted(contacts.keys())
for key in contacts:
value = contacts[key]
if key == "Miranda" and 'mobile' in value:
print(f"contact: {key}, mobile number: {value['mobile']}")
else:
print(f"contact: {key}, mobile number: {value}")
contacts_inv = {value: key for key, value in contacts.items() if isinstance(value, str)}
print(contacts_inv)
I tried using the standard inverse {v: k for k, v in contacts.items() if isinstance(value, str)} method but that didn't inverse all the values, only the first 3.
You have to adjust your inversion logic to deal with nested dictionaries explicitly:
Here's how you might implement it:
contacts_inv = {}
for key, value in contacts.items():
if isinstance(value, str):
if value in contacts_inv:
contacts_inv[value].append(key)
else:
contacts_inv[value] = [key]
elif isinstance(value, dict):
for sub_key, sub_value in value.items():
if sub_value in contacts_inv:
contacts_inv[sub_value].append(key)
else:
contacts_inv[sub_value] = [key]
print(contacts_inv)