Reputation: 11
Apologies for the potentially noobish question.
I have this dict:
info = {'a': [u'option1'], 'b': [u'option2', u'option3'], 'c': [], 'd': [], 'e': [], 'f': [u'option4', u'option5', u'option6', u'option7', u'option8', u'option9', u'option10', u'option11'], 'g': [], 'h': []}
I need to make a query with each value. In Python what is the best way to get the values?
I currently do this:
keys = info.keys ()
for i in keys:
for j in info [i]:
# Make query with j
I think it can be done better. Thank you very much!
Upvotes: 0
Views: 88
Reputation: 59240
You can iterate through the keys and values of a dict using items()
.
for i, js in info.items():
for j in js:
# Make query with j
(In Python 2 you might prefer to use iteritems()
instead of items()
.)
If you don't need to make use of the keys at all, you could just use values
(or itervalues
for Python 2).
for js in info.values():
for j in js:
# Make query with j
Maybe a list comprehension would work for you; it is impossible to tell without knowing what "Make query with j" entails.
Upvotes: 3
Reputation: 93
You can do it this way:
for vals in info.values():
for j in vals:
# make queries with j
You can get the list of all the values like this:
values = [x for vals in info.values() for x in vals]
Then you can use
for j in values:
# make queries with j
Upvotes: 0
Reputation: 91
For Python 2.x
for key,values in info.iteritems():
print keys,values
Using dict.iteritems() you can iterate through the keys and values in dictionary and make queries or anything.
Dict: name of the dictionary*
Upvotes: 0
Reputation: 54303
Do you want to iterate over the list elements in every value? If you don't use the key, you can use dict.values()
directly:
>>> [option for v in info.values() for option in v]
['option1', 'option2', 'option3', 'option4', 'option5', 'option6', 'option7', 'option8', 'option9', 'option10', 'option11']
Upvotes: 1
Reputation: 2076
for key, value in info.items():
#do something with either the key, value or both
Upvotes: 0