user10613120
user10613120

Reputation: 29

Adding a value to an existing key in python

I have a list:

Marks =[
    [12345,75,'English'],
    [23452,83,'Physics'],
    [23560,81,'Statistics'],
    [23415,61,'Computer'],
    [23459,90,'Physics'],
    [12345,75,'Computer'],
    [23452,100,'Statistics']
]

and I want to make a dictionary where the class name is the key and the two numbers are the values. I can make the initial dictionary like this:

for i in list1:
    dict1[i[2]]=i[0],i[1]

But when I print the dictionary, only one of each of the pairs of numbers associated is printed. I'm looking for a result like:

{ 
  'English' : [[12345,75]],
  'Physics' : [[23452,83], [23459,90]],
  'Statistics' : [[23560,81], [23452,100]],
  'Computer' : [[23415,61], [12345,75]]
}

Is there any way I can extend the values associated with a key?

I tried:

if i[2] in dict1:
    dict1.extend

Upvotes: 0

Views: 75

Answers (3)

accdias
accdias

Reputation: 5372

You can use comprehensions to achieve that easily:

>>> Marks = [[12345,75,'English'], [23452,83,'Physics'], [23560,81,'Statistics'], [23415,61,'Computer'], [23459,90,'Physics'], [12345,75,'Computer'], [23452,100,'Statistics']]
>>> d = { m[2]: [m[0], m[1]] for m in Marks }
>>> d
{'English': [12345, 75], 'Physics': [23459, 90], 'Statistics': [23452, 100], 'Computer': [12345, 75]}
>>> 

EDIT: This will create the dictionary taking into account those repeated keys.

d = {}
for mark in Marks:
     if not mark[2] in d:
             d[mark[2]] = [[mark[0], mark[1]]]
     else:
             d[mark[2]] += [[mark[0], mark[1]]]

The dictionary will end up with this shape:

>>> d
{'English': [[12345, 75]], 'Physics': [[23452, 83], [23459, 90]], 'Statistics': [[23560, 81], [23452, 100]], 'Computer': [[23415, 61], [12345, 75]]}
>>> 

Upvotes: 1

Rakesh
Rakesh

Reputation: 82785

Using collections.defaultdict

Ex:

from collections import defaultdict

Marks = [[12345,75,'English'], [23452,83,'Physics'], [23560,81,'Statistics'], [23415,61,'Computer'], [23459,90,'Physics'], [12345,75,'Computer'], [23452,100,'Statistics']]

result = defaultdict(list)
for i in Marks:
    result[i[-1]].append(i[:2])
print(result)

Output:

defaultdict(<type 'list'>, {'Statistics': [[23560, 81], [23452, 100]], 'Physics': [[23452, 83], [23459, 90]], 'Computer': [[23415, 61], [12345, 75]], 'English': [[12345, 75]]})

Upvotes: 2

holidayfun
holidayfun

Reputation: 356

You can only have a single value for a key in your dictionary. But you could save the two values as either a list or a tuple like so:

for i in list1:
    dict1[i[2]]=i[0:1]

or

for i in list1:
    dict1[i[2]]=(i[0], i[1])

Upvotes: 1

Related Questions