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

前端 未结 14 1756
面向向阳花
面向向阳花 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 06:52

    If you want to access both the key and value, use the following:

    Python 2:

    for key, value in my_dict.iteritems():
        print(key, value)
    

    Python 3:

    for key, value in my_dict.items():
        print(key, value)
    

提交回复
热议问题