Understanding Multiple Dictionary Comparisons in Python

Asked 1 years ago, Updated 1 years ago, 414 views

I'm a Python beginner.

The values are in the same group from left to right.For example, in group 1, one of a in A is one group, and another group is two of a in B, one of b in C, and one of a in D, and there are four groups.

dict1={"group1":["A", "B", "C", "D", "group2":["E", "F", "G", "H", "I"], "group3":["J", "K", "L", "M", "N"]}
dict2={"group1":["a", "a", "b", "a", "a"], "group2":["a", "a", "a", "a", "a"], "group3":["a", "a", "a", "b", "b"]}
dict3={"group1":["1", "2", "1", "1", "1", "group2":["1", "1", "2", "3", "4"], "group3":["1", "1", "2", "2", "2"]}
The following is what you would like to do with the dictionaries dict1, dict2, and dict3.

それぞれ Match the values in each group
②A discrimination is made on how many different kinds exist (in group 1, there are two of a, two of a, and one of b, so there are three kinds), and capital letters of the alphabet are written for each group.
③Generate and output results

I would like to print as follows.

result=
4# Indicates how many types are available
group2
a1 E,F#dict2,dict3,dict1 information.
a2G
a3H
a4 I

3
group1
a1 A,D
a2B
b1 C

group3
a1J,K
a2L
b2M,N

I thought about the program proposal despite my lack of knowledge, but I can't show the capital letters for each group in order of the largest type.Please let me know.
set_list = {k:len(set(zip(dict2[k], dict3[k]))))) for direct2.keys()}
result=[]
for set_list.keys():
result.append(set_list[r])
result.append(list(set(zip(dict2[r],dict3[r])))
result.append(dict1[r])

# Output
[3, [('a', '1'), ('a', '2', ('b', '1'), ['A', 'B', 'C', 'D'], 4, [('a', '3', ('a', '1'), ('a', '2', ('a', '4')], ['E', 'F', 'G', 'H', 'I'], 3, 'a', 'a', '2, 'a', 'a', 'a', 'a', '2, 'a', 'a', 'a', 'a', '2, 'a', 'a', '2, 'a', 'b', 'a', 'a', '2,'', '

python

2023-02-24 02:09

1 Answers

You can get the results you want by using the dict2,3 values as keys and putting the corresponding dict1 values in the list.


dict1={"group1":["A", "B", "C", "D", "group2":["E", "F", "G", "H", "I"], "group3":["J", "K", "L", "M", "N"]}
dict2 = {"group1": ["a", "a", "b", "a", "a" ] "group2": ["a", "a", "a", "a", "a", "a" ] "group3": ["a", "a", "a", "b", "b" ]}
dict3={"group1":["1", "2", "1", "1", "1", "group2":["1", "1", "2", "3", "4"], "group3":["1", "1", "2", "2", "2"]}

for key indict1.keys():

    # Key a few values and list the corresponding values of 1
    sub_d = {}
    for d1, d2, d3 in zip (dict1[key], dict2[key], dict3[key]):
        sub_k=(d2,d3)
        if sub_k not in sub_d:
            sub_d[sub_k] = [ ]
        sub_d[sub_k].append(d1)

    # output of results
    print(len(sub_d))
    print(key)
    fork, vin sub_d.items():
        print(k[0], k[1], *v)
"""
3
group1
a1 AD
a2 B
b1 C
4
group2
a1EF
a2G
a3H
a4 I
3
group3
a1JK
a2L
b 2 MN
"""


2023-02-24 10:03

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.