asked 41.0k views
3 votes
You are given a dictionary aDict that maps integer keys to integer values. Write a Python function that returns a list of keys in aDict that map to dictionary values that appear exactly once in aDict. This function takes in a dictionary and returns a list. Return the list of keys in increasing order. If aDict does not contain any values appearing exactly once, return an empty list. If aDict is empty, return an empty list. For example: If aDict

asked
User Bongeh
by
7.5k points

1 Answer

0 votes

Final answer:

The Python function iterates over the dictionary, counts the occurrence of each value, and stores keys with unique values in a list, which is returned sorted. If aDict is empty or lacks unique values, an empty list is returned.

Step-by-step explanation:

To write a Python function that identifies keys in a dictionary (aDict) where their associated values appear exactly once, you can follow these steps:

  • Initialize an empty list to store keys with unique values.
  • Use a loop to count the occurrences of each value in the dictionary.
  • Find those keys with values that have a count of one and add them to the list.
  • Return the list of keys, sorted in increasing order.

Here is a sample Python function that implements this logic:

def uniqueValues(aDict):
# Count how many times each value appears in the dictionary
value_counts = {}
for key in aDict:
if aDict[key] in value_counts:
value_counts[aDict[key]] += 1
else:
value_counts[aDict[key]] = 1
# Collect keys that have a unique value (appear exactly once)
unique_keys = []
for key, value in aDict.items():
if value_counts[value] == 1:
unique_keys.append(key)
# Return the list of unique keys in increasing order
return sorted(unique_keys)

If the dictionary aDict is empty or there are no unique values, the function will return an empty list.

answered
User Steven Lemmens
by
8.8k points