How can I use if/else in a dictionary comprehension?

后端 未结 4 1748
长发绾君心
长发绾君心 2020-11-28 20:40

Does there exist a way in Python 2.7+ to make something like the following?

{ something_if_true if condition else something_if_false for key, value in d         


        
4条回答
  •  无人及你
    2020-11-28 20:46

    Another example in using if/else in dictionary comprehension

    I am working on data-entry desktop application for my own office work, and it is common for such data-entry application to get all entries from input widget and dump it into a dictionary for further processing like validation, or editing which we must return selected data from file back to entry widgets, etc.

    The first round using traditional coding (8 lines):

    entries = {'name': 'Material Name', 'maxt': 'Max Working Temperature', 'ther': {100: 1.1, 200: 1.2}}
    
    a_dic, b_dic = {}, {}
    
    for field, value in entries.items():
        if field == 'ther':
            for k,v in value.items():
                b_dic[k] = v
            a_dic[field] = b_dic
        else:
            a_dic[field] = value
        
    print(a_dic)
    “ {'name': 'Material Name', 'maxt': 'Max Working Temperature', 'ther': {100: 1.1, 200: 1.2}}”
    

    Second round I tried to use dictionary comprehension but the loop still there (6 lines):

    entries = {'name': 'Material Name', 'maxt': 'Max Working Temperature', 'ther': {100: 1.1, 200: 1.2}}
    
    for field, value in entries.items():
        if field == 'ther':
            b_dic = {k:v for k,v in value.items()}
            a_dic[field] = b_dic
        else:
            a_dic[field] = value
        
    print(a_dic)
    “ {'name': 'Material Name', 'maxt': 'Max Working Temperature', 'ther': {100: 1.1, 200: 1.2}}”
    

    Finally, with a one-line dictionary comprehension statement (1 line):

    entries = {'name': 'Material Name', 'maxt': 'Max Working Temperature', 'ther': {100: 1.1, 200: 1.2}}
    
    a_dic = {field:{k:v for k,v in value.items()} if field == 'ther' 
            else value for field, value in entries.items()}
        
    print(a_dic)
    “ {'name': 'Material Name', 'maxt': 'Max Working Temperature', 'ther': {100: 1.1, 200: 1.2}}”
    

    I use python 3.8.3

提交回复
热议问题