Home > Mobile >  How to create dictionary of connecting column if dictionary value present in list
How to create dictionary of connecting column if dictionary value present in list

Time:12-08

How can I count the number of times a value appears in a dictionary where the values are taken from a list in Python? and create new dictionary

For example, given the following list:

list = [1,2,3,4,5,6,7,8,9]

    dict = {1:[15,2,72,7,62,71,13,6,153,154,73,39],2:[16,15,61,1,71,72,39,4,74,14,69,5],3:      [69,85,19,13,42,46,14,62,103,4,153,86],4:[70,20,14,66,13,33,87,61,85,86,97,5],5:[9,65,69,62,13,42,144,85,41,6,14,31]}

   

if have tryed but i did not work

   

with open ('connection2.csv','w', newline='') as csv_file:
        writer = csv.writer(csv_file)
        for key, value in dict.items():
            if value in list:
                writer.writerow([key])

      I want to create a new dictionary that counts the number of items from list value present in dictionary value. The result should look like this:

disered output

dict = {1:3,2:3,3:1,4:1,5:2}

CodePudding user response:

Using a dict comprehension:

my_list = [1,2,3,4,5,6,7,8,9]
my_dict = {1: [15,2,72,7,62,71,13,6,153,154,73,39], 2: [16,15,61,1,71,72,39,4,74,14,69,5], 3: [69,85,19,13,42,46,14,62,103,4,153,86],4: [70,20,14,66,13,33,87,61,85,86,97,5], 5: [9,65,69,62,13,42,144,85,41,6,14,31]}

result = {k: len(set(v).intersection(my_list)) for k, v in my_dict.items()}

# print(result) --> {1: 3, 2: 3, 3: 1, 4: 1, 5: 2}

CodePudding user response:

Compare each dictionary's values ​​with the main list with a for loop and get the length of the matches as value.

my_list = [1,2,3,4,5,6,7,8,9]
my_dict = {1:[15,2,72,7,62,71,13,6,153,154,73,39],2:[16,15,61,1,71,72,39,4,74,14,69,5],3:      [69,85,19,13,42,46,14,62,103,4,153,86],4:[70,20,14,66,13,33,87,61,85,86,97,5],5:[9,65,69,62,13,42,144,85,41,6,14,31]}

final={}
for k,v in my_dict.items():
    final.update({k:len([i for i in my_list if i in v])})
# print(final) -- > {1: 3, 2: 3, 3: 1, 4: 1, 5: 2}

or one line:

final = {k:len([i for i in my_list if i in v]) for k,v in my_dict.items()}
# print(final) -- > {1: 3, 2: 3, 3: 1, 4: 1, 5: 2}
  • Related