简体   繁体   中英

Python to print out to excel or csv from a for loop

I have working on this code:

Section = {'East':['Alan','Bob'],
           'North':['Alan','Michael'],
           'South':['Tom'],
           'West':['Bob','Michael','Tom']}
Name = {'Alan':['Subaru','Chevvy','Honda'],
        'Bob':['Toyota','Honda','Camry'],
        'Michael':['Camry','Ford'],
        'Tom':['Ford','Toyota']}
Inventory = {'East':['Toyota','Honda','Camry'],
             'North':['Ford','Chevvy','Ferrari','Subaru'],
             'South':['Subaru','Acura','Lexus','BMW'],
             'West':['Ford','Subaru','Camry']}



for name,sections in Section.items():
    for section in sections:
        haveInventory = Name[name]
        needInventory = Inventory[section]
        
        for inventory in needInventory:
            if inventory not in haveInventory:
                print(str(name) + ' ' + str(section) + ' ' + str(inventory))
  1. Not sure what but the code does not run
  2. How can i export the result out to excel or csv file with the following format: Alan East Camry Alan East Honda Tom South Subaru

I have changed these two lines:

for name,sections in Section.items():
    for section in sections:

To


for sections,names in Section.items():
    for name in names:

import csv

Section = {'East':['Alan','Bob'],
           'North':['Alan','Michael'],
           'South':['Tom'],
           'West':['Bob','Michael','Tom']}
Name = {'Alan':['Subaru','Chevvy','Honda'],
        'Bob':['Toyota','Honda','Camry'],
        'Michael':['Camry','Ford'],
        'Tom':['Ford','Toyota']}
Inventory = {'East':['Toyota','Honda','Camry'],
             'North':['Ford','Chevvy','Ferrari','Subaru'],
             'South':['Subaru','Acura','Lexus','BMW'],
             'West':['Ford','Subaru','Camry']}


f1 = open('file.csv','w')
writer=csv.writer(f1, delimiter='\t',lineterminator='\n',)
for sections,names in Section.items():
    for name in names:
        haveInventory = Name[name]
        needInventory = Inventory[sections]
        
        for inventory in needInventory:
            if inventory not in haveInventory:
                print(str(name) + ' ' + str(sections) + ' ' + str(inventory))
                writer.writerow([f"{name} {sections} {inventory}"])

Alan East Toyota
Alan East Camry
Alan North Ford
Alan North Ferrari
Michael North Chevvy
Michael North Ferrari
Michael North Subaru
Tom South Subaru
Tom South Acura
Tom South Lexus
Tom South BMW
Bob West Ford
Bob West Subaru
Michael West Subaru
Tom West Subaru
Tom West Camry

Have a look at this:

for name,sections in Section.items(): # ('East', ['Alan','Bob'])
    for section in sections:
        haveInventory = Name[name] # Name['East'] Causes error
        needInventory = Inventory[section]

As you can see, in that particular iteration, you are trying to get value of the key 'East' from the dictionary 'haveInventory' , but that dictionary doesn't have that key.

Section = {'East': ['Alan', 'Bob'],
           'North': ['Alan', 'Michael'],
           'South': ['Tom'],
           'West': ['Bob', 'Michael', 'Tom']}
Name = {'Alan': ['Subaru', 'Chevvy', 'Honda'],
        'Bob': ['Toyota', 'Honda', 'Camry'],
        'Michael': ['Camry', 'Ford'],
        'Tom': ['Ford', 'Toyota']}
Inventory = {'East': ['Toyota', 'Honda', 'Camry'],
             'North': ['Ford', 'Chevvy', 'Ferrari', 'Subaru'],
             'South': ['Subaru', 'Acura', 'Lexus', 'BMW'],
             'West': ['Ford', 'Subaru', 'Camry']}

import pandas as pd
result=pd.DataFrame()
NAME = []
SECTION = []
INVENTORY = []
for section, names in Section.items():
    for name in names:
        haveInventory = Name[name]
        needInventory = Inventory[section]

        for inventory in needInventory:
            if inventory not in haveInventory:
                print(str(name) + ' ' + str(section) + ' ' + str(inventory))
                NAME.append(name)
                SECTION.append(section)
                INVENTORY.append(inventory)

data = {'Name': NAME, 'Section': SECTION, 'inventory': INVENTORY}
result = pd.DataFrame(data, columns=['Name', 'Section', 'inventory'])
result.to_csv('result.csv')
from time import gmtime, strftime, time
import csv
current_time = strftime("%Y-%m-%d_%H-%M-%S", gmtime())


with open('result_'+ current_time + '.csv','w') as f1:
    writer = csv.writer(f1, delimiter='\t',lineterminator='\n',)
    for section, names in Section.items():
        for name in names:
            haveInventory = Name[name]
            needInventory = Inventory[section]

            for inventory in needInventory:
                if inventory not in haveInventory:
                    print(str(name) + ' ' + str(section) + ' ' + str(inventory))
                    writer.writerow([str(name) + ' ' + str(section) + ' ' + str(inventory)])

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