Python Forum

Full Version: Organizing Data in Dictionary
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hello All,

I'm trying to pull the data from excel and organize it inside the dictionary for further usage. some how I'm failing, please help.

Input File is like:
No Ticket User
1 P12334 Raju
2 P12335 Usha
3 P12336 Suri
4 P12337 Ben
5 P12338 Raju
6 P12339 Roy
7 P12340 Ben
8 P12341 Raju
9 P12342 Roy
10 P12343 Usha
11 P12344 Ben
12 P12345 Roy
13 P12346 Usha

I need output as:
In a dictionary
Raju - P12334, P12337, P12338
Ben - P12340, P12343
Usha - P12350, P12351, P12327

But I'm not getting it, the dictionary is having only one ticket information for each user (key). I'm unable to append or add values. Could you please help?

values = {}
for i in range(sheet.nrows):
    row = sheet.row_values(i)
    print(row[2])
    values[row[2]]={
        'Backlogs':row[1]
    }

#pprint.pprint(values)
print(values)
There is no reason to have "Backlogs" in the dictionary if it is the one and only entry. To have more than on entry per user, use a list.
values = {}
for i in range(sheet.nrows):
    row = sheet.row_values(i)
    this_value=row[2]  ## save looking up row[2] multiple times
    print(this_value)
    if this_value not in values:
        values[this_value] = []
    values[this_value].append(row[1])
 
#pprint.pprint(values)
print(values)
Another possibility is to use .setdefault method (instead of rows 6-8):

values.setdefault(this_value, []).append(row[1])
Thank you both of you. It worked