Reputation: 337
I have a dictionary that contains 9 items, it's called users. Now would it be possible to do this, which is completely functional:
for x in range (0, 9):
print users[x]
In one line of code with something like
print users[x for x in range (0, 9)]
That gives syntax error. So is it possible to do it this way or maybe I need to use lambda functions or something? Thanks
Upvotes: 0
Views: 61
Reputation: 8897
You need to put print
inside loop, like this
for k in users:
print (k)
or if you want to more flexibility you can use methods of dict
, like keys
or values
, and you can do like this for more readble output:
for k in users:
print (k : x[k])
Upvotes: 0
Reputation: 36354
Two notes before I come to the point:
First,
[x for x in whatever]
is totally redundant,
whatever
would yield the same indices.
In your case, it would be equivalent to
print users[range(0,9)]
which is the same as
print users[range(9)]
which won't work, because users
doesn't support indexing with a list
.
Second,
you shouldn't use a dictionary if your keys are integers that are consecutive and start at 0. That's a list.
What you can do is just use the different methods of a dictionary, e.g.
print users.items()
or
print users.keys()
or even
print "\n".join("key %s has value %s" % item for item in users.items())
if you want your code to look more like it was written in a functional language. Which Python is not. It has functional aspects. It's not always easiest to read when used in a functional matter. I would just stick with your original code.
Upvotes: 2