Big Data/Analytics Zone is brought to you in partnership with:

Mark is a graph advocate and field engineer for Neo Technology, the company behind the Neo4j graph database. As a field engineer, Mark helps customers embrace graph data and Neo4j building sophisticated solutions to challenging data problems. When he's not with customers Mark is a developer on Neo4j and writes his experiences of being a graphista on a popular blog at http://markhneedham.com/blog. He tweets at @markhneedham. Mark is a DZone MVB and is not an employee of DZone and has posted 553 posts at DZone. You can read more from them at their website. View Full User Profile

# Python: for/list comprehensions and dictionaries

08.14.2013
| 2016 views |

I’ve been working through Coursera’s Linear Algebra course and since all of the exercises are in Python I’ve been playing around with it again.

One interesting thing I learnt is that you can construct dictionaries using a list comprehension type syntax.

For example, if we start with the following dictionaries:

```>>> x = { "a": 1, "b":2 }
>>> y = {1: "mark", 2: "will"}
>>> x
{'a': 1, 'b': 2}
>>> y
{1: 'mark', 2: 'will'}```

We might want to create a new dictionary which links from the keys in x to the values in y. In this case we work out the mapping by finding the key in y which corresponds with each value in x.

So the map we want to see at the end should look like this:

`{"a": 'mark', "b": 'will'}`

We can iterate over the keys/values of a dictionary by calling Dictionary#iteritems like so:

```>>> for key, value in x.iteritems():
...   print (key, value)
...
('a', 1)
('b', 2)```

I thought I might be able to construct my new dictionary by converting this into a for comprehension:

```>>> [key:value for key, value in x.iteritems()]
File "<stdin>", line 1
[key:value for key, value in x.iteritems()]
^
SyntaxError: invalid syntax```

Unfortunately that didn’t work but I came across an interesting post from which I learned that using curly brackets might do the trick.

```>>> {key:value for key, value in x.iteritems()}
{'a': 1, 'b': 2}
>>> type({key:value for key, value in x.iteritems()})
<type 'dict'>```

I wanted to make the final dictionary take a lookup into account which we can do like this:

```>>> {key:y[value] for key, value in x.iteritems()}
{'a': 'mark', 'b': 'will'}```

Apparently this is known as a dictionary comprehension and has been in the language since version 2.7.

I’m sure this is old news to seasoned Python developers but I’d not come across it before so to me it’s pretty neat!

Published at DZone with permission of Mark Needham, author and DZone MVB. (source)

(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)

Tags:
"Starting from scratch" is seductive but disease ridden
-Pithy Advice for Programmers