Create a dictionary with list comprehension

前端 未结 14 1994
灰色年华
灰色年华 2020-11-21 07:07

I like the Python list comprehension syntax.

Can it be used to create dictionaries too? For example, by iterating over pairs of keys and values:

mydi         


        
14条回答
  •  情书的邮戳
    2020-11-21 07:51

    Yes, it's possible. In python, Comprehension can be used in List, Set, Dictionary, etc. You can write it this way

    mydict = {k:v for (k,v) in blah}
    

    Another detailed example of Dictionary Comprehension with the Conditional Statement and Loop:

    parents = [father, mother]
                
    parents = {parent:1 - P["mutation"] if parent in two_genes else 0.5 if parent in one_gene else P["mutation"] for parent in parents}
    

提交回复
热议问题