-1

i have a dictionary as

count = {'lt60': {'a': 0, 'b': 0, 'c': 0, 'd': 0}, 'ge60le90': {'a': 4, 'b': 0, 'C': 0, 'd': 0}, 'gt90': {'a': 0, 'b': 1, 'c': 2, 'd': 1} }

i want to write this dictionary in a CSV format like this ..as you can see in this picture csv file format

what i want is pic the keys from lt60, ge60le90, gt90 and want to write them in a row. like i pick 'a' and its value from all the nested dictionaries and write its value in that row.

Jodocus
  • 7,493
  • 1
  • 29
  • 45
viscabar
  • 63
  • 2
  • 8
  • 1
    Possible duplicate of [How can I convert JSON to CSV?](https://stackoverflow.com/questions/1871524/how-can-i-convert-json-to-csv) – vmg Mar 21 '18 at 12:01
  • @MikeScotty I tried but its not working thatwhy I'm asking as I'm a beginner in python. – viscabar Mar 21 '18 at 12:14
  • If you tried something and "it's not working" then post your attempt (or at least a MCVE) with the exact description of how it's "not working". Also please replace your excel screenshot with the real expected csv (csv is a text format you know ?) – bruno desthuilliers Mar 21 '18 at 12:38
  • @brunodesthuilliers I'm a newbie to this platform and also to python ..so I don't know that I need to post my code also...actually i was trying it using csv module and i don't know that how to pick up the keys and values from the nested dictionaries..:) Hope you can understand :) – viscabar Mar 21 '18 at 13:31

3 Answers3

2

You can use pandas to do this:

import pandas as pd

count = {'lt60': {'a': 0, 'b': 0, 'c': 0, 'd': 0},
         'ge60le90': {'a': 4, 'b': 0, 'c': 0, 'd': 0},
         'gt90': {'a': 0, 'b': 1, 'c': 2, 'd': 1} }

df = pd.DataFrame(count).rename_axis('relation_type').reset_index()

df = df.rename(columns={'ge60le90': 'confidence<90',
                        'gt90': 'confidence>90',
                        'lt60': 'confidence<60'})

df.to_csv('out.csv', index=False)

#   relation_type  confidence<90  confidence>90  confidence<60
# 0             a              4              0              0
# 1             b              0              1              0
# 2             c              0              2              0
# 3             d              0              1              0
jpp
  • 159,742
  • 34
  • 281
  • 339
0

This problem can be simplified by iterating through your dict to pull out your keys and values of those keys

count = {'lt60': {'a': 0, 'b': 0, 'c': 0, 'd': 0},
         'ge60le90': {'a': 4, 'b': 0, 'c': 0, 'd': 0},
         'gt90': {'a': 0, 'b': 1, 'c': 2, 'd': 1} }

# Create outfile
f = open("C:\\Users\\<USER>\\Desktop\\OUT.csv","w")
# Write first row
f.write(",a,b,c,d\n")

# Iterate through keys
for keys in count:
    print(keys)
    f.write(keys + ",")

    KEYS = count[keys]
# Iterate though values
    for values in KEYS:
        print(KEYS[values])
        f.write(str(KEYS[values]) + ",")
    f.write("\n")
f.close()
Jerome Paddick
  • 399
  • 1
  • 14
0

Another way of doing it would be to utilize csv module. (Note that in your dictionary you have an upper case C which I corrected in my code below):

import csv

lookup = {'ge60le90': 'confidence<90','gt90': 'confidence>90', 'lt60': 'confidence<60'}

count = {'lt60': {'a': 0, 'b': 0, 'c': 0, 'd': 0}, 'ge60le90': {'a': 4, 'b': 0, 'c': 0, 'd': 0}, 'gt90': {'a': 0, 'b': 1, 'c': 2, 'd': 1} }

# Getting keys from dictionary that match them with titles below.
rowKeys = [k for k in count['lt60'].keys()] 
titles = [['relation type'] + list(lookup[k] for k in count.keys())]

# Getting all row variable values for every title.
rows = [[count[k][i] for k in count.keys()] for i in rowKeys]

# Concatenating variables and values.
fields = [[rowKeys[i]] + rows[i] for i in range(len(rowKeys))]

# Concatenating final output to be written to file.
result = titles + fields
print("Final result to be written: ")
for r in result:
    print(r)

# Writing to file.
with open("output.csv", "w", newline="") as outFile:
    writer = csv.writer(outFile, delimiter=';',quotechar='|', quoting=csv.QUOTE_MINIMAL)
    writer.writerows(result)

Note that the ; delimiter works for European Windows and might not work for you. In this case, use , instead.

Vasilis G.
  • 7,556
  • 4
  • 19
  • 29