-1

I need to pass only values from list of dictionaries to a function. The list of dictionaries looks like this

[ { "positive" : 515, "neutral" : 22, "negative": 1515 },
  { "positive": 15555, "neutral": 2525, "negative": 111}
  ......
]

and I need to get all the numbers for one key into a list so I can pass it to this function (below). (it shouldn't look like this, this is the only solution I was capable of). I need some more efficient solution, maybe something with map function or list comprehensions, but I have no idea how to use these.

bar_chart.add('neutral', [ dictList[0]['neutral'],dictList[1]['neutral'],dictList[2]['neutral'] ....... ['neutral'],dictList[23]['neutral'] ] )
bar_chart.add('positive', [ dictList[0]['positive'],dictList[1]['positive'],dictList[2]['positive'], ......... ,dictList[23]['positive'] ] )
Will Ness
  • 70,110
  • 9
  • 98
  • 181
janjilecek
  • 37
  • 5

2 Answers2

0
    dictlist =[ { "positive" : 515, "neutral" : 22, "negative": 1515 },
             { "positive": 15555, "neutral": 2525, "negative": 111}]

    poslist = []
    neutlist = []
    neglist = []
    for stuff in dictlist:
            poslist.append(stuff["positive"])
            neutlist.append(stuff["neutral"])
            neglist.append(stuff["negative"])

you will have only the values in the corresponding lists then...

sront
  • 1
  • 1
0

This should take care of it in one line:

[bar_chart.add(key,[item[key] for item in dictList]) for key in dictList[0].keys()]

The comprehension assembles lists for all common keys in your list of dictionaries(reffered to asitem) and then passes in the key and values into your bar_chart.add method.

The comprehension by itself produces a list of the common key values:

>>> [[item[key] for item in dictList] for key in dictList[0].keys()]
[[515, 15555], [22, 2525], [1515, 111]]

Good Luck!

Moe Jan
  • 369
  • 1
  • 4
  • 16