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

前端 未结 14 1728
面向向阳花
面向向阳花 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:51

    For python 3 If you want to get only the keys use this. Replace print(key) with print(values) if you want the values.

    for key,value in my_dict:
      print(key)
    
    0 讨论(0)
  • 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)
    
    0 讨论(0)
  • 2020-12-04 06:53

    easily change the position of your keys and values,then use values to get key, in dictionary keys can have same value but they(keys) should be different. for instance if you have a list and the first value of it is a key for your problem and other values are the specs of the first value:

    list1=["Name",'ID=13736','Phone:1313','Dep:pyhton']
    

    you can save and use the data easily in Dictionary by this loop:

    data_dict={}
    for i in range(1, len(list1)):
         data_dict[list1[i]]=list1[0]
    print(data_dict)
    {'ID=13736': 'Name', 'Phone:1313': 'Name', 'Dep:pyhton': 'Name'}
    

    then you can find the key(name) base on any input value.

    0 讨论(0)
  • 2020-12-04 06:55

    As simple as that:

    mydictionary={'keyname':'somevalue'}
    result = mydictionary.popitem()[0]
    

    You will modify your dictionary and should make a copy of it first

    0 讨论(0)
  • 2020-12-04 06:58

    Iterate over dictionary (i) will return the key, then using it (i) to get the value

    for i in D:
        print "key: %s, value: %s" % (i, D[i])
    
    0 讨论(0)
  • 2020-12-04 07:01

    You should iterate over keys with:

    for key in mydictionary:
       print "key: %s , value: %s" % (key, mydictionary[key])
    
    0 讨论(0)
提交回复
热议问题