سؤال

I have a list that looks like this

[(u'will', 332), (u'Indian', 398), (u'#AAP', 409), (u'Rahul', 430), (u'Modi', 441)]

I want to plot this on a bar chart using google charts. Google needs the data in the following format -

[
['Year', 'Austria'],
['2003',  1336060],
['2004',  1538156],
['2005',  1576579],
['2006',  1600652],
['2007',  1968113],
['2008',  1901067]

]

How can I convert my list to this format? I understand that I can say list.add to add the headers at the first position. But how do I change the remaining part of the list? If you are curious to know how I got the list in that format here is the code for that -

f = open('data/convertcsv.json')
        data = json.loads(f.read())
        f.close()
        wordDict = {}
        for row in data:
            # print row['sentiment']
            wordList = row['text'].split()
            for word in wordList:
                if len(word) < 4: continue
                if word in wordDict: wordDict[word] += 1
                else: wordDict[word] = 1
        sorted_list = sorted(wordDict.iteritems(), key=operator.itemgetter(1))
        final_list = sorted_list[-5:]
هل كانت مفيدة؟

المحلول

Did you try to just json.dumps your list? The format is already correct (tuples get converted to JSON arrays just fine).

All you need to do is add the header (with insert, not add though)

نصائح أخرى

I'm not entirely clear on whether you're having problems with Python data structures, or just with exporting to JSON. Anyway, if you want to get your existing data looking exactly like the example, all you have to do is:

original_data = [(u'will', 332), (u'Indian', 398), (u'#AAP', 409), (u'Rahul', 430), (u'Modi', 441)]

reworked_data = [['x_label', 'y_label']]

for item in original_data:
    reworked_data.append(list(item))

reworked_data
Out[4]: 
[['x_label', 'y_label'],
 [u'will', 332],
 [u'Indian', 398],
 [u'#AAP', 409],
 [u'Rahul', 430],
 [u'Modi', 441]]

To export to JSON, you can just do:

json.dumps(reworked_data)
Out[6]: '[["x_label", "y_label"], ["will", 332], ["Indian", 398], ["#AAP", 409], ["Rahul", 430], ["Modi", 441]]'

But as Matti says, it's not necessary to convert the tuples to lists to do that, you could just insert the header/labels into your original list.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top