[Tutor] how to iterate through a dictionary and assign list values?

Asokan Pichai pasokan at talentsprint.com
Thu Dec 5 06:51:55 CET 2013


On Thu, Dec 5, 2013 at 9:43 AM, Jared Nielsen <nielsen.jared at gmail.com>wrote:

> I want to create a dictionary, assign it keys, then iterate through a for
> loop and assign the dictionary values from a list. I'm trying this, but
> it's not working:
>
> dictionary = {"one", "two", "three"}
>
This creates a set. and NOT a dictionary. Please remember that a dictionary
is (unordered) iterable collection of key-value pairs.

To initialise a dictionary and give it values you have to do
dictionary = { key1:value1, key2:value2} .


> list = [1,2,3]
>
> for key in dictionary:
>     for value in list:
>         dictionary[key] = value
>
> I get this error:
> TypeError: 'set' object does not support item assignment
>
Now I hope the error message makes sense.

What am I doing wrong? Any help is greatly appreciated.
>
I am not trying to tell you what to do as that would greatly depend on what
you are trying to do. But

d = {key:value for key, value in zip(keys, values)}

and

d = dict(zip(keys, values))

are worth studying.

Asokan Pichai

"So, if I look into my foggy crystal ball at the future of computing
science education, I overwhelmingly see the depressing picture of "Business
as usual". The universities will continue to lack the courage to teach hard
science, they will continue to misguide the students, and each next stage
of infantilization of the curriculum will be hailed as educational
progress."

Edsger W Dijkstra in Dec 1988, in an article titled "on the cruelty of
really teaching Computer Science" Link:
http://www.cs.utexas.edu/~EWD/transcriptions/EWD10xx/EWD1036.html
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20131205/1cc1c22c/attachment.html>


More information about the Tutor mailing list