简体   繁体   中英

Trying to Access keys in Dict from their values

I'm importing a CSV to a dictionary, where there are a number of houses labelled (IE 1A, 1B,...) Rows are labelled containing some item such as 'coffee' and etc. In the table is data indicating how much of each item each house hold needs.

Excel screenshot

What I am trying to do it check the values of the key value pairs in the dictionary for anything that isn't blank (containing either 1 or 2), and then take the key value pair and the ' PRODUCT NUMBER ' (from the csv) and append those into a new list.

I want to create a shopping list that will contain what item I need, with what quantity, to which household.

the column containing ' week ' is not important for this

I import the CSV into python as a dictionary like this:

import csv
import pprint

from typing import List, Dict

input_file_1 = csv.DictReader(open("DATA CWK SHOPPING DATA WEEK 1 FILE B.xlsb.csv"))

table: List[Dict[str, int]] = [] #list

for row in input_file_1:
    string_row: Dict[str, int] = {} #dictionary
    for column in row:
        string_row[column] = row[column]
    table.append(string_row)

I found on 'geeksforgeeks' how to access the pair by its value. however when I try this in my dictionary, it only seems to be able to search for the last row.

# creating a new dictionary
my_dict ={"java":100, "python":112, "c":11}
 
# list out keys and values separately
key_list = list(my_dict.keys())
val_list = list(my_dict.values())
 
# print key with val 100
position = val_list.index(100)
print(key_list[position])

I also tried to do a for in range loop, but that didn't seem to work either:

for row in table:
    if row["PRODUCT NUMBER"] == '1' and row["Week"] == '1':
        for i in range(8):
            if string_row.values() != ' ':
                print(row[i])

Please, if I am unclear anywhere, please let me know and I will clear it up!!

Here is a loop I made that should do what you want.

values = list(table.values())
keys = list(table.keys())
new_table = {}
index = -1
for i in range(values.count("")):
  index = values.index("", index +1)
  new_table[keys[index]] = values[index]

If you want to remove those values from the original dict you can just add in d.pop(keys[index]) into the loop

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