Home > OS >  Selecting values from CSV file which are not already in an inventory list
Selecting values from CSV file which are not already in an inventory list

Time:04-28

I have an inventory of phone extensions in a list. I also have phone extensions that are assigned to users in a csv file.

I am looking to compare the assigned numbers (dictionary) to the numbers in the inventory (list). I would like to print out any numbers that are not already assigned from the inventory list.

Here is the flow I've been working with, first I read the CSV into a dictionary. Next, I loop through the phone field and push it to an open list, where I remove duplicates before running the compare.

But my program is not providing the output I am looking for.

Here is the CSV:

Directory_Num01,13037,Office,Luis
Directory_Num02,13036,AP,Jess
Directory_Num03,13040,Loading Dock,Loading Dock
Directory_Num04,13036,Lobby,Guest
Directory_Num05,13099,Office,Office
Directory_Num06,13037,Office,Office
Directory_Num07,13036,Lobby,Beth

Here is the code:

import csv

inventory_numbers = ['13037', '13036', '13085', '13079', '13040', '13099', '13055']

with open(r'\file.csv', newline='') as f:
    empty_dict = {}
    empty_list = []
    without_duplicates = []
    index = 0

    reader = csv.reader(f)
    for row in reader:
        empty_dict[row[0]] = {'phone_number':row[1], 'location':row[2], 'description':row[3]}

    for catalog, directoy_info in empty_dict.items():
        tele = f"{directoy_info['phone_number']}"
        empty_list = tele

    for element in empty_list:
        if element not in without_duplicates:
            without_duplicates.append(element)
    print(without_duplicates)

CodePudding user response:

I suggest a simpler approach using set data type.

inventory_numbers = ['13037', '13036', '13085', '13079', '13040', '13099', '13055']
assigned_numbers = []

with open(r'file.csv', newline='') as f:
    reader = csv.reader(f)
    for row in reader:
        assigned_numbers.append(row[1])

print('Un-assinged numbers')
print(set(inventory_numbers) - set(assigned_numbers))

Output:

Un-assinged numbers
{'13079', '13055', '13085'}

Suggestions:

  • In your code empty_list = tele is odd one for me. Here you are replacing information. Please check.
  • dict are wonderful but in your case, it is not needed.
  • Related