简体   繁体   中英

create python array from dict of dicts

new one for me -- I'm assuming this is fairly easy, but I've never worked with arrays before, so I'm curious as to how it works.

I have a dict of dicts, like so:

{'bob': {'a':1, 'b':2, ...}, 'joe': {'a':2, 'c':3, ...} ...}

I'd like to turn it into an array so I can write it to a CSV and then turn it into a heatmap using R. I was trying to cheat and just write each nested dict to an individual row, but of course that won't work because not every key is present in every nested dict. simple, right?

desired output would look like (in tabular form):

,a,b,c
bob,1,2,0
joe,2,0,3

If your columns are fixed, you could simply do something like:

cols = ['a', 'b', 'c']
csv.writerow([''] + cols)
for name, values in data.iteritems():
    csv.writerow([name] + [values.get(c, 0) for c in cols])

let's suppose you have 3 predefined keys, you can use the get function of the dict to get the value or a default one if the key is not in the dict:

headers = ('a', 'b', 'c')
for key, values in dict.item():
     print ','.join([values.get(h, '') for h in headers])

Others have already answered the printing, but assume fixed headers. To get the column headers from the dict:

columns = sorted(set(column for subdict in dict_of_dicts.itervalues() for column in subdict))

Or, more verbosely:

column_set = set()
for subdict in dict_of_dicts.itervalues():
  for column in subdict:
    column_set.add(column)
columns = sorted(column_set)

To create the array in one long line, just for fun, not recommended:

array = [[''] + columns] + [[key] + [subdict.get(column, 0) for column in columns] for key, subdict in dict_of_dicts.iteritems()]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM