Question

I have this code:

#//Running my argument to check if the item in list is in dictionary and returning    this + corresponding value in dictionary//#
for key in n:
    if DICT.get(key):
        print ((key) + ' : ' + DICT[key])
    else:
        print((key) + ' : ' + "Not Available")

#Writing to .cvs file       
with open('test_write.csv', 'w') as fp:
    a = csv.writer(fp)
    a.writerows(n)

I want to have the result in the above for loop written to .csv.
At the moment I am getting each letter of the first part of the code in separate columns.
I need to have the both one in each column..
I suggest that I need to convert the for loop to a dict? But I could be wrong...

Any ideas on how to do this the easiest?

EDIT:
Using your sugestion:

    with open('test_write.csv', 'w') as fp:
        a = csv.writer(fp)
        for key in n:
        if DICT.get(key):
            print ((key) + ' : ' + DICT[key])
            a.writerow(n)
        else:
            print((key) + ' : ' + "Not Available")
            a.writerow(DICT.get(n,"Not Available") for name in n)

I am not getting what I was expecting
I am getting 4 rows of my list n. With no indication of the value in the DICT. What am I doing wrong...

Was it helpful?

Solution

writerows takes a list of iterables. Try using writerow. From the looks of things, n is a dict, so to get a row of headers and a row of values, do:

a.writerow(n.keys())
a.writerow(n.values())

You could write a.writerow(n) for the first line, but I prefer to show this a little more explicitly.

And a little shortcut to add all the default values:

names = ['list','of','all','expected','keys']
data = {'list':'A', 'of':'zoo', 'keys':'foo'}
default = dict.fromkeys(names,"Not Available")
default.update(data)
data = default

Leaving data with the contents:

{'all': 'Not Available', 'of': 'zoo', 'list': 'A', 'expected': 'Not Available', 'keys': 'foo'}

EDIT:

Given DICT = {1:a, 2:b, 3:c, 4:d} and a list n = [1, 2, 5, 6], just do:

a.writerow(n)
a.writerow(DICT.get(name,"Not Available") for name in n)

will print two rows to your CSV file, one with the key names in n, and one with the values from DICT, or the words "Not Available" if a particular key is not in DICT.

EDIT2:

You are trying too hard - DICT.get will take care of whether an entry exists or not:

with open('test_write.csv', 'w') as fp:
    a = csv.writer(fp)
    a.writerow(n)
    a.writerow(DICT.get(name,"Not Available") for name in n)

Here is the same code, with a little more verbose form:

with open('test_write.csv', 'w') as fp:
    a = csv.writer(fp)
    # write row of header names
    a.writerow(n)

    # build up a list of the values in DICT corresponding to the keys in n
    values = []
    for name in n:
        if name in DICT:
            values.append(DICT[name])
        else:
            values.append("Not Available")
    # or written as a list comprehension:
    # values = [DICT[name] if name in DICT else "Not Available" for name in n]
    # 
    # or just use DICT.get, which does the name checking for us, and chooses the 
    # default value if the key is not found
    # values = [DICT.get(name, "Not Available") for name in n]

    # now write them out
    a.writerow(values)

    # or finally, the list build and writerow call all in one line
    # a.writerow(DICT.get(name,"Not Available") for name in n)

EDIT:

    # to write out the transpose of the previous lines (that is, instead of 
    # a line of names and a line of the matching values, a line for each
    # name-value pair), use Python's zip builtin:
    for nameValueTuple in zip(n,values):
        a.writerow(nameValueTuple)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top