honesty20
honesty20

Reputation: 61

Create a non unique python dictionary

I am making a program that user will enter their score and unit load for that course, then store them in a dictionary like {score:unit_load}. Then, I'll loop through the dictionary and multiple each score by its unit load. My problem is this: dictionaries always returns unique key unlike lists. Someone may have the same score in more than one course but my dictionary will certainly remove any repetition of score from the sequence. I need help on how to create the dictionary in a non-unique manner. I also tried creating two lists and storing score in one list and unit load in another... My problem becomes how to loop through the two lists and multiple the pairwise items. I tried something like

dic = {}
last_list = []
while True:
    score = input("Enter score 
    and press -1 when you 
    finish entering your score: ")
    if score=='-1':
       break
    unit_load =int(input("Enter 
    unitt load"))
    dic[score]=unit_load
for score, unit_load in dic.items():
    multiple = score*unit_load
    last_list.append(multiple)
print(last_list)

The returned dictionary always discards any similar key(score) as some people may have the same score in more than one subject. Can someone show me how to convert the dictionary so that it always returns all the score like in list without discarding similar score to make itself unique?

Upvotes: 1

Views: 872

Answers (2)

Ahmad
Ahmad

Reputation: 11

I dont think you need to use dictionaries for this case you can simply follow two array approach something like:

import numpy as np

course_len = int(input('Enter total no. of courses'))

#initialize np arrays

score = np.ndarray(course_len, int)
unit_load = np.ndarray(course_len, int)

dic = {}

#fill in you arrays with a loop

while j<course_len:
    score[j] = input('enter score')
    j +=1 



while k<course_len:
    unit_load[k] = input('enter unitload')
    k +=1 

#fill in the product
for i in range(course_len):

    dic[i] = score[i]*unit_load[i]

    i +=1

print(dic)

the final dictionary will contain the final product of the score and the unit load in a nice indexed way. Hope this is plain and simple.

Upvotes: 0

Thomas
Thomas

Reputation: 181745

This is not a good use for dictionaries, as you noticed. Consider using a list of tuples:

items = []
while True:
  ...
  items.append((score, unit_load))
for score, unit_load in items:
  ...

And since you also tried the two lists approach, here's how that would look:

scores = []
unit_loads = []
while True:
  ...
  scores.append(score)
  unit_loads.append(unit_load)
for score, unit_load in zip(scores, unit_loads):
  ...

The zip function takes two (or more) lists (or iterables) and pairs the elements up into a single iterable of tuples.

Upvotes: 2

Related Questions