Home > Mobile >  Python - Homework assignment for a dynamic dictionary
Python - Homework assignment for a dynamic dictionary

Time:11-07

"Try to create a dynamic dictionary of some data with repeating keys and one with repeating values, find what is the value that is repeated and how many times it is repeated as a final print for the user"

I have typed the following code as an example:

from itertools import chain

# initialising dictionary
ini_dict = {"Name": 'John', "Age": 43, "Name": 'Mark',"Age": 43,"Occupation": "Plumber" }
init_dict2 = {"Name": 'John', "Age": 43, "Name": 'Mark',"Age": 43,"Occupation": "Plumber", "Occupation": "Teacher", "Age": 35}

# printing initial_dictionary
print("initial_dictionary", str(ini_dict))
print("initial_dictionary", str(init_dict2))

rev_dict = {}
for key, value in ini_dict.items():
    rev_dict.setdefault(value, set()).add(key)

result = set(chain.from_iterable(
    values for key, values in rev_dict.items()
    if len(values) > 1))

rev2_dict = {}
for key, value in ini_dict.items():
    rev2_dict.setdefault(value, set()).add(key)

result = set(chain.from_iterable(
    values for key, values in rev2_dict.items()
    if len(values) > 1))

# printing result
print("resultant key", str(result))
print("resultant key", str(result))

This the output:

"C:\Python lectures\TestovProekt\venv\Scripts\python.exe" "C:/Python lectures/TestovProekt/Homework 6.1.py"
initial_dictionary {'Name': 'Mark', 'Age': 43, 'Occupation': 'Plumber'}
initial_dictionary {'Name': 'Mark', 'Age': 35, 'Occupation': 'Teacher'}
resultant key set()
resultant key set()

I need help on what exact code to type so that the final print result is what value is repeated and how many times, cause I'm very new to all this so I don't know exactly I need to type that I am missing.

CodePudding user response:

A dictionary cannot have duplicate keys. The second assignment overwrites the first. That's why you get:

{"Name": 'John', "Age": 43, "Name": 'Mark'} == {'Name': 'Mark', 'Age': 43}
>>> True

Because of that the homework question doesn't make much sense to me


Update (see comments)

Here is a way of counting repeating values (in this cases prices) of a dictionary.

fruit_prices = {"apple": 5, "banana": 5, "cherry": 1, "durian": 25}

fruits_per_price = {}
# iterate over all fruit, price combinations
for fruit, price in fruit_prices.items():
    if price in fruits_per_price:
        # if you already have a list of fruits for that price, append the fruit
        fruits_per_price[price].append(fruit)
    else:
        # if not, create a new fruit list
        fruits_per_price[price] = [fruit]
        
# the count for each value is now equal to the length of the fruit list
...
  • Related