Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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)

>Solution :

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.
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading