How can I get dictionary key as variable directly in Python (not by searching from value)?

前端 未结 14 1757
面向向阳花
面向向阳花 2020-12-04 06:19

Sorry for this basic question but my searches on this are not turning up anything other than how to get a dictionary\'s key based on its value which I would prefer not to us

14条回答
  •  失恋的感觉
    2020-12-04 07:01

    What I sometimes do is I create another dictionary just to be able whatever I feel I need to access as string. Then I iterate over multiple dictionaries matching keys to build e.g. a table with first column as description.

    dict_names = {'key1': 'Text 1', 'key2': 'Text 2'}
    dict_values = {'key1': 0, 'key2': 1} 
    
    for key, value in dict_names.items():
        print('{0} {1}'.format(dict_names[key], dict_values[key])
    

    You can easily do for a huge amount of dictionaries to match data (I like the fact that with dictionary you can always refer to something well known as the key name)

    yes I use dictionaries to store results of functions so I don't need to run these functions everytime I call them just only once and then access the results anytime.

    EDIT: in my example the key name does not really matter (I personally like using the same key names as it is easier to go pick a single value from any of my matching dictionaries), just make sure the number of keys in each dictionary is the same

提交回复
热议问题