简体   繁体   中英

Using a list comprehension used as a conditional filter nested in a dictionary comprehension

I am trying to create a dictionary of dictionaries that is being created by filtering a known dictionary and the conditional comes from a list. This would be dynamic, so the data within the list and the known dictionary will constantly change.

list = {5: ('t', 'a'), 7: ('s', 'o')}

known_dict = {('s', 'a'): 105, ('s', 'e'): 2, ('s', 'h'): 5, ('t', 'a'): 21,
              ('t', 'e'): 8, ('t', 'h'): 21}

Given the above, I am trying to create a dictionary where the keys are the first character of the tuples in the list, and the values are the corresponding first character tuples from the known dictionary.

desired_output = {s: {('s', 'a'): 105, ('s', 'e'): 2, ('s', 'h'): 5}, 
                  t: {('t', 'a'): 21, ('t', 'e'): 8, ('t', 'h')}}

The code I have to try to achieve this is:

desired_output = {
    key[0]: {
        key: value for key, value in known_dict.items() 
        if key[0] == [a for a,b in list.values()]
    } 
    for key in known_dict
}

The issue of is that when the list comprehension occurs, the result is a list which and not individual characters, so my result is an empty dictionary because the conditional is not met.

If there is something I am missing or if there is a different approach that I should consider, please let me know.

The following should work. Iterate over the values in "list" (which you shold rename) and collect the items from "known_dict" along the way, not the other way round:

desired_output = {
    v[0]: {k_: v_ for k_, v_ in known_dict.items() if k_[0]==v[0]} 
    for v in list.values()
}
# {'t': {('t', 'a'): 21, ('t', 'e'): 8, ('t', 'h'): 21}, 
#  's': {('s', 'a'): 105, ('s', 'e'): 2, ('s', 'h'): 5}}

Sidenote: "list" is a terrible variable name. First, it shadows the built-in type list . Second, you are using it for a dict .

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