简体   繁体   中英

Check if Values from List of Dictionaries are Unique Without Keys

I have a dictionary like the one bellow:

d = {
    "00068693": [
        {"LABP": "022012"},
        {"LAOS": "022012"},
        {"LAOS": "022012"},
        {"LAOS": "022012"},
        {"LAOS": "022012"},
        {"LAOS": "022012"},
        {"LABC": "022012"},
        {"LACL": "022012"},
        {"LACL": "022012"},
        {"LACL": "022012"},
        {"LACL": "349309"},
    ],
    "00084737": [
        {"LABP": "022012"},
        {"LAOS": "022012"},
        {"LABC": "022012"},
        {"LACL": "022012"},
    ]
}

The goal of my code is to check if an ID (ex.: "00068693" ) has a unique code (ex.: "022012" ) on all files (ex.: "LAOS" ).

So the output for this example should be:

ID: "00068693" has different codes.
ID: "00084737" has a unique code.

But, how do I check this?

Because I don't know what files the ID has, so I can't access through each key of the list.

I'm not trying to compare the elements, just the values for each dict, but each one of them are on a different list index and I don't know the keys.

You can Check if all elements in a list are identical . The question is which list? Well, you need to construct a list of the codes of all files. We don't really care what the files are, just their codes:

for ID, files_list in d.items():
    codes = [list(file_dict.values())[0] for file_dict in files_list]
    print(codes)
    print(f"The codes for ID {ID} are all equal? {all_equal(codes)}")

With your example dict, this is the result:

['022012', '022012', '022012', '022012', '022012', '022012', '022012', '022012', '022012', '022012', '349309']
The codes for ID 00068693 are all equal? False
['022012', '022012', '022012', '022012']
The codes for ID 00084737 are all equal? True

* all_equal above is any of the options in the accepted answer of the duplicate

Assuming your dictionary is called file_codes , this is how you get the results:

for k, v in file_codes.items():
    if len(set([i[j] for i in v for j in i])) != 1:
            print(f"IDS: {k} has different codes")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM