Home > Enterprise >  How to access elements in list of dictionaries?
How to access elements in list of dictionaries?

Time:09-28

I’m working with a CSV file that looks as follows:

POS,Transaction id,Product,Quantity,Customer,Date
1,E100,TV,1,Test Customer,9/19/2022
2,E100,Laptop,3,Test Customer,9/20/2022
3,E200,TV,1,Test Customer,9/21/2022
4,E300,Smartphone,2,Test Customer,9/22/2022
5,E300,Laptop,5,New Customer,9/23/2022
6,E300,TV,1,New Customer,9/23/2022
7,E400,TV,2,ABC,9/24/2022
8,E500,Smartwatch,4,ABC,9/25/2022

In order to grab elements out of it this gets each line into a callable line by assignment:

with open(obj.file_name.path, 'r') as f:
                rdr = csv.DictReader(f)
                for row in rdr:
                    pos = row['POS']
                    product = row['Product']
                    transaction_id = row['Transaction id']
                    quantity = row['Quantity']
                    customer = row['Customer']
                    date = row['Date']

                
                try:
                    product_obj = Product.objects.get(name__iexact=product)
                except Product.DoesNotExist:
                    product_obj = None
                

For example to print each row from the CSV I can now type:

pos, transaction_id, product, quantity, customer, transaction_id, date = row
print(row)

Resulting in this terminal output:

file is being uploaded
{'POS': '1', 'Transaction id': 'E100', 'Product': 'TV', 'Quantity': '1', 'Customer': 'Test Customer', 'Date': '9/19/2022'}
{'POS': '2', 'Transaction id': 'E100', 'Product': 'Laptop', 'Quantity': '3', 'Customer': 'Test Customer', 'Date': '9/20/2022'}
{'POS': '3', 'Transaction id': 'E200', 'Product': 'TV', 'Quantity': '1', 'Customer': 'Test Customer', 'Date': '9/21/2022'}
{'POS': '4', 'Transaction id': 'E300', 'Product': 'Smartphone', 'Quantity': '2', 'Customer': 'Test Customer', 'Date': '9/22/2022'}
{'POS': '5', 'Transaction id': 'E300', 'Product': 'Laptop', 'Quantity': '5', 'Customer': 'New Customer', 'Date': '9/23/2022'}
{'POS': '6', 'Transaction id': 'E300', 'Product': 'TV', 'Quantity': '1', 'Customer': 'New Customer', 'Date': '9/23/2022'}
{'POS': '7', 'Transaction id': 'E400', 'Product': 'TV', 'Quantity': '2', 'Customer': 'ABC', 'Date': '9/24/2022'}
{'POS': '8', 'Transaction id': 'E500', 'Product': 'Smartwatch', 'Quantity': '4', 'Customer': 'ABC', 'Date': '9/25/2022'}

So it totally works, what I’m struggling with however is how to access one particular dictionary say I want to only access a particular dictionary, the one containing POS: 1, or to see all dictionaries containing the product TV. How would I go about this?

Edit:

Even though it is possible to extract product, using it in assignment of product_obj it always returns None. Does anyone know what the reason for this might be?

CodePudding user response:

rdr = csv.DictReader(...) is (probably) dynamically creating the entries as it reads them

Either collect them all into a list() and index them at the line you're after [index] or break when you find the line with the content you want

for row in csv.DictReader(...):
    if row.get(search_key) == search_value:
        break  # or return from a function
raise ValueError(f"failed to find {search_key}")

CodePudding user response:

I wasn't able to run your coding on my computer but there are a lot of ways of doing what you are attempting to do. I would recommend:

https://blog.finxter.com/how-to-filter-a-dictionary-in-python/#:~:text=The Most Pythonic Way) 1 Method 1: Simple,4 Method 4: Filter By Dictionary Comprehension

If possible, I would recommend using pandas.

import pandas as pd
file = "Your file path here"
df = pd.read_csv(file)

#To filter for 1
print(df[df['POS']==1])
#To filter for TV
print(df[df['Product']=='TV'])
  • Related