Skip to content
Advertisement

search and find from csv with dict

I have a csv file containing info like this:

1087,c6d537e112156be1afbb8a5a85221ff4d95e2461f83f03425549ff42dee7a278

I also have a dictionary in python containing similar info :

{'danial': '277375b99e186c72ac38ac47b03199038342fe0389be8765476fa2be0c5b5649', 'elham': 'c6d537e112156be1afbb8a5a85221ff4d95e2461f83f03425549ff42dee7a278'}

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 :

danial,1087
elham,1011

Advertisement

Answer

Here’s an idea:

  1. Create another, inverted dictionary which maps your values to their keys:
inverted_dict = { hash_string : key for key, hash_string in YOUR_DICT.items() }
  1. Open your csv file, iterate the lines of it, and extract the first and second elements of each line:
with open(YOUR_CSV_FILENAME) as fp:
    for line in fp:
        val, hash_string = line.strip().split()
  1. Check if the second element is in your inverted dict, and if so, print the appropriate mapping:
        if hash_string in inverted_dict:
            print(f"{inverted_dict[hash_string]}, {val}")
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement