rahul
rahul

Reputation: 591

Add new key value pair in a Python Dictionary

I am really stuck with a problem here, I am new to python and using it for a typical requirement. I want to add key value pairs into a dictionary within a loop for eg:

Eg_dict={}
for row in iterable:
    dict={row[1],row[2]}

This code doesn't do what I want to achieve, this just adds the very last record of the iterable into the dictionary, its easy to assume that my code is reading each record from iterable and rewriting the dictionary over and over again.

So my question is simple how to add all the records from the iterable in the dictionary? This would be the default behavior of an array in unix.

P.S: the iterable here can be assumed as a csv.reader object and I am trying to insert the second and third columns into the dictionary.

Upvotes: 0

Views: 13237

Answers (2)

Martijn Pieters
Martijn Pieters

Reputation: 1124848

Use dictionary assignment:

for row in iterable:
    Eg_dict[row[1]] = row[2]

or ever replace the whole code with a dict comprehension:

Eg_dict = {row[1]: row[2] for row in iterable}  # python 2.7 and up

or

Eg_dict = dict(row[1:3] for row in iterable)    # python 2.3 and up

If each row has a fixed number of entries, you can use tuple assignment:

for key, value in row:  # two elements

or

for _, key, value in row:  # three elements, ignore the first

to make a loop more readable. E.g. {key: value for _, key, value in iterable}.

Your code instead creates a new set object (just unique values, no keys) each loop, replacing the previous one.

Upvotes: 8

Yuval Adam
Yuval Adam

Reputation: 165340

You can use a nice list comprehension for this:

d = dict([(row[1], row[2]) for row in iterable])

This will work in any Python version.

If you use 2.7+ or 3, you can use the cleaner dict comprehension:

d = {row[1]:row[2] for row in iterable}

Upvotes: 2

Related Questions