Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
149 views
in Technique[技术] by (71.8m points)

python - 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 (I.E. 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!!

question from:https://stackoverflow.com/questions/65908660/trying-to-access-keys-in-dict-from-their-values

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...