Get name of dictionary

后端 未结 6 1707
感情败类
感情败类 2021-02-13 22:19

I find myself needing to iterate over a list made of dictionaries and I need, for every iteration, the name of which dictionary I\'m iterating on.

Here\'s an MWE (the co

6条回答
  •  花落未央
    2021-02-13 22:35

    If you want to read name and value

    dictionary={"name1":"value1","name2":"value2","name3":"value3","name4":"value4"}
    for name,value in dictionary.items():
        print(name)
        print(value)
    

    If you want to read name only

    dictionary={"name1":"value1","name2":"value2","name3":"value3","name4":"value4"}
    for name in dictionary:
        print(name)
    

    If you want to read value only

    dictionary={"name1":"value1","name2":"value2","name3":"value3","name4":"value4"}
    for values in dictionary.values():
        print(values)
    

    Here is your answer

    dic1 = {"dic":1}
    dic2 = {"dic":2}
    dic3 = {"dic":3}
    dictionaries = [dic1,dic2,dic3]
    for i in range(len(dictionaries)):
      my_var_name = [ k for k,v in locals().items() if v == dictionaries[i]][0]
      print(my_var_name)
    

提交回复
热议问题