Home > other >  Python Dictionary, Reading a list and appending the values of a dictionary
Python Dictionary, Reading a list and appending the values of a dictionary

Time:09-30

I have a sample input csv file (made into a list) that looks like this:

Alfa,Beta,Charlie,Delta,Echo
A1,B1,C1,D1,AX1
A2,B2,C2,D2,BX1
A3,B3,C3,D3,CX1
A4,B4,C4,D4,BX1/CX1
A4,B4,C4,D4,CX1/AX1
A4,B4,C4,D4,AX1/BX1

Then my sample code looks like this:

#feed is the list I posted above

column_numbers = 'Echo'

ID_dict = {"AX1" : "AA1,AA2,AA3",
           "BX1" : "BB1,BB2,BB3",
           "CX1" : "CC1,CC2,CC3"
           }

for row in feed: 
    column_key = row[column_numbers]
    for item in ID_dict[column_key].split(','):
        row[column_numbers] = item
        print(item)

If I run this and print(items), The result I will get for the "Echo" column will be:

AA1
AA2
AA3
BB1
BB2
BB3
CC1
CC2
CC3

However since the list I posted has "BX1/CX1, CX1/AX1 and AX1/BX1" how do I make it where it reads the BX1/CX1 and then appends the correct values from the dictionary. For example, if it says BX1/CX1, it should output:

BB1
BB2
BB3
CC1
CC2
CC3

Or if it says BX1/AB1/CX1, it will use the dictionary and then add the values and it should output:

BB1
BB2
BB3
AA1
AA2
AA3
CC1
CC2
CC3

CodePudding user response:

cat sample.csv                                                                                                                                                            
Alfa,Beta,Charlie,Delta,Echo
A1,B1,C1,D1,AX1
A2,B2,C2,D2,BX1
A3,B3,C3,D3,CX1
A4,B4,C4,D4,BX1/CX1
A4,B4,C4,D4,CX1/AX1
A4,B4,C4,D4,AX1/BX1

import csv

with open('sample.csv') as csv_file:
    column_numbers = 'Echo'
    ID_dict = {"AX1" : "AA1,AA2,AA3",
           "BX1" : "BB1,BB2,BB3",
           "CX1" : "CC1,CC2,CC3"
           }
    reader = csv.DictReader(csv_file)
    for row in reader:
        if row[column_numbers]:
            for ky in row[column_numbers].split('/'):
                for item in ID_dict[ky].split(','):
                    print(item)



AA1
AA2
AA3
BB1
BB2
BB3
CC1
CC2
CC3
BB1
BB2
BB3
CC1
CC2
CC3
CC1
CC2
CC3
AA1
AA2
AA3
AA1
AA2
AA3
BB1
BB2
BB3

CodePudding user response:

Strings have a split() function to create an array by splitting the string on some separator.

> 'abc'.split('/')   # The return value is always an array
['abc']
> 'a/b/c'.split('/')
['a', 'b', 'c']
  • Related