Python Forum
Looping through dictionary and comparing values with elements of a separate list.
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Looping through dictionary and comparing values with elements of a separate list.
#4
(Jun-22-2018, 01:12 PM)Mr_Keystrokes Wrote: Hmm, this doesn't take into account the instances where the 2 elements being compared are the same.

let's take the check in a function
import csv

def check_line(line, isolate):
    my_set = set(line)
    return len(my_set & isolate) == len(my_set)

with open('isolate_file.txt') as f:
    new_isolate = {line.strip() for line in f}

with open('snapper_data.csv') as sd:
    rdr = csv.reader(sd)
    my_isolates = [line[1:] for line in rdr if check_line(line[1:-1], new_isolate)]
             
print(my_isolates)
you can do it also like this
import csv

with open('isolate_file.txt') as f:
    new_isolate = {line.strip() for line in f}

with open('snapper_data.csv') as sd:
    rdr = csv.reader(sd)
    my_isolates = [line[1:] for line in rdr if line[1] in new_isolate and line[2] in new_isolate]
             
print(my_isolates)    
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply


Messages In This Thread
RE: Looping through dictionary and comparing values with elements of a separate list. - by buran - Jun-22-2018, 01:46 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
  Replace values in Yaml file with value in dictionary PelleH 1 2,079 Feb-11-2025, 09:51 AM
Last Post: alexjordan
  Assigning cycle values in a list nmancini 3 933 Sep-16-2024, 09:35 PM
Last Post: deanhystad
  remove duplicates from dicts with list values wardancer84 27 5,409 May-27-2024, 04:54 PM
Last Post: wardancer84
  Sort a list of dictionaries by the only dictionary key Calab 2 1,399 Apr-29-2024, 04:38 PM
Last Post: Calab
Question Using Lists as Dictionary Values bfallert 8 2,158 Apr-21-2024, 06:55 AM
Last Post: Pedroski55
  unable to remove all elements from list based on a condition sg_python 3 1,630 Jan-27-2024, 04:03 PM
Last Post: deanhystad
  Dictionary in a list bashage 2 1,345 Dec-27-2023, 04:04 PM
Last Post: deanhystad
  filtering a list of dictionary as per given criteria jss 5 1,651 Dec-23-2023, 08:47 AM
Last Post: Gribouillis
  need to compare 2 values in a nested dictionary jss 2 1,663 Nov-30-2023, 03:17 PM
Last Post: Pedroski55
  Copying the order of another list with identical values gohanhango 7 2,488 Nov-29-2023, 09:17 PM
Last Post: Pedroski55

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020