I have a csv file containing info like this:
JavaScript
2
1
1087,c6d537e112156be1afbb8a5a85221ff4d95e2461f83f03425549ff42dee7a278
2
I also have a dictionary in python containing similar info :
JavaScript
2
1
{'danial': '277375b99e186c72ac38ac47b03199038342fe0389be8765476fa2be0c5b5649', 'elham': 'c6d537e112156be1afbb8a5a85221ff4d95e2461f83f03425549ff42dee7a278'}
2
how can I search values of dict in my csv file and print matching row in CSV to keys in dictionary in out put for example :
JavaScript
3
1
danial,1087
2
elham,1011
3
Advertisement
Answer
Here’s an idea:
- Create another, inverted dictionary which maps your values to their keys:
JavaScript
2
1
inverted_dict = { hash_string : key for key, hash_string in YOUR_DICT.items() }
2
- Open your csv file, iterate the lines of it, and extract the first and second elements of each line:
JavaScript
4
1
with open(YOUR_CSV_FILENAME) as fp:
2
for line in fp:
3
val, hash_string = line.strip().split()
4
- Check if the second element is in your inverted dict, and if so, print the appropriate mapping:
JavaScript
3
1
if hash_string in inverted_dict:
2
print(f"{inverted_dict[hash_string]}, {val}")
3