Faqiha Ali
Faqiha Ali

Reputation: 11

How do I assign multiple values taken from user to a single key stored in a dictionary in python?

I am trying to create a number of lists that store a number of values. Each list is mentioned as class in my code. I want to add values for each key, one by one, in the dictionary that is taken from a user.

This is my code so far:

n = input('Enter the number of classe: ')
class_count = int(n)
listDict = {}

for i in range(1, class_count):
    listDict["class_" + str(i)] = []
    print(listDict)

Output:

Enter the number of classe: 4
{'class_1': []}
{'class_1': [], 'class_2': []}
{'class_1': [], 'class_2': [], 'class_3': []}

Upvotes: 1

Views: 62

Answers (3)

datawrestler
datawrestler

Reputation: 1567

You could create a userid for each user, use that as the key and then assign each class value to a list for that user such as the following:

def generateuserid():
    """
    generate user id for each user input
    :return: userid
    """
    for i in range(100):
        yield 'user{}'.format(i)

# initiate generator
users = generateuserid()

n=input('Enter the number of classe: ')
listDict = {}

# for each user, retrieve next id
user = next(users)

for i in range(1,int(n)):
    if user in listDict.keys():
        listDict[user].append('class_{}'.format(i))
    else:
        listDict[user] = ['class_{}'.format(i)]
    print(listDict) #{'user1': ['class_1', 'class_2', 'class_3', 'class_4', 'class_5', 'class_6', 'class_7', 'class_8', 'class_9']}

Upvotes: 0

yampelo
yampelo

Reputation: 512

You need to iterate to class_count+1 since even though you start a 1, it doesn't mean the range function will iterate one additional time, it'll actually simply iterate one less time.

Also you should probably use an OrderedDict in order to retain order of the classes:

from collections import OrderedDict
listDict = OrderedDict()
class_count = 4
for i in range(1,class_count+1):
     listDict["class_"+str(i)] = []

print listDict
>>>OrderedDict([('class_1', []), ('class_2', []), ('class_3', []), ('class_4', [])])

Upvotes: 1

Uri Goren
Uri Goren

Reputation: 13700

You should take a look at python's defaultdict construct:

from collections import defaultdict
listDict = defaultdict(list)

And then, just write

listDict['class_{i}'.format(i=0)].append(value)

No need to initialize listDict['class_{i}'.format(i=0)] to be []

Upvotes: 0

Related Questions