python - print multidimensional dictionary with repeating key -
i new python , using python 2. built multidimensional dictionary looks this:
targets = {house: {n: {red: {a:1}, garden: {n: 6}}} {great: {a: {very: {adv:12}, so: {adv: 5}, a: {det: 3}}}} etc.
basically there 4 nested dictionaries entries of 'third' dictionary ({red: {}, horse: {} etc) can consist of arbitrary number of items. so, number of items in dictionary varies.
now, write dictionary file, preferably csv-file. output file should display entries in tab-separated manner, each line starting outmost key. example:
house n red 1 house n garden n 6 great adv 12 great adv 5 great det 3
i know, there lot of posts printing multidimensional dictionaries, have not found 1 (yet) outmost key printed during every iteration. tried include code snippets provided other questions concerning multidimensional dictionaries did not work far.
i managed write dictionary normal .txt-file in dictionary format loop:
for target in targets_dict: results.write(str(target) + str(targets_dict[str(target)]) + '\n')
or write csv-file using csvwriter (i know there dictwriter, not work properly):
w = csv.writer(results, delimiter = '\t') target in targets_dict.iteritems(): w.writerow(target)
obviously, pretty basic , iteration not enter inner dictionaries.
trying modified solution has been posted related problem (recursively traverse multidimensional dictionary, dimension unknown) resides in 'expected character buffer object'-error.
for k,v in sorted(targets_dict.items(),key=lambda x: x[0]): if isinstance(v, dict): results.write(" ") + ("%s %s") % (k, v)
every suggestion or hint appreciated me understand logic behind this, able figure out.
here simple solution. idea loop through dict, list, create tsv file list, because know nest depth (4, seems ok). below not optimized speed, , doesn't check existence anywhere, idea.
import csv targets = {'house': {'n': {'red': {'a':1}, 'garden': {'n': 6}}}, 'great': {'a': {'very': {'adv':12}, 'so': {'adv': 5}, 'a': {'det': 3}}}} open('targets.tsv', 'w', newline='\n') tsvfile: writer = csv.writer(tsvfile, delimiter='\t') t in targets: u in targets[t]: v in targets[t][u]: w in targets[t][u][v]: #print [t, u, v, w, targets[t][u][v][w]] writer.writerow([t, u, v, w, targets[t][u][v][w]])
prints:
['house', 'n', 'red', 'a', 1] ['house', 'n', 'garden', 'n', 6] ['great', 'a', 'very', 'adv', 12] ['great', 'a', 'so', 'adv', 5] ['great', 'a', 'a', 'det', 3]
and creates tsv file:
house n red 1 house n garden n 6 great adv 12 great adv 5 great det 3
edit: updated code according comment in op (the keys in outermost dictionary unique , should treated keys targets
).
Comments
Post a Comment