cc6g11
cc6g11

Reputation: 487

Iterating out the values in a list of dictionaries PYTHON

I have a list of dictionaries. Each has a key, and a 3 value list. Each value is an ADC reading, I have a function to take and spit out the converted value.

I would like to take each value and convert it with this function, however.

for value in my_list[0].itervalues():
  print value

This prints the values as a list, but I want to take each value individually and pass it off to the function to be converted

 for value in my_list:
      print value

This prints out each dictionary

I am not sure how to nest these loops all together to take the individual values and append the current list of dictionaries with the converted values or generate a separate list of dictionaries altogether. Appending would be more efficient I suppose.

Upvotes: 1

Views: 59

Answers (1)

Kasravnd
Kasravnd

Reputation: 107347

You can use map function to apply your function on all value items :

for value in my_list[0].itervalues():
  print map(your_func,value)

And if you want to create a new dictionary you can do it within a dict comprehension :

new_dict={k:map(your_func,val) for k, val in your_dict.iteritems()}

Also you may note that this depends on your function signature and your values for example if your function accept more than 1 argument you can not use map here.

Example :

>>> def my_func(a,b):
...   return a+b
... 
>>> l=[(1,2),(3,4),(5,6)]
>>> map(my_func,l)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: my_func() takes exactly 2 arguments (1 given)

In that case you can use a list comprehension :

>>> [my_func(i,j) for i,j in l]
[3, 7, 11]

Upvotes: 2

Related Questions