Python Generate a dynamic dictionary from the list of keys

前端 未结 7 1368
长发绾君心
长发绾君心 2021-02-09 02:38

I do have a list as given below -

keyList1 = [\"Person\", \"Male\", \"Boy\", \"Student\", \"id_123\", \"Name\"]
value1 = \"Roger\"

How can I ge

7条回答
  •  青春惊慌失措
    2021-02-09 03:01

    Use tuple(keyList1) as key. (tuples are immutable and therefore can be dict keys).

    You will have a world of headache with the nested dict approach. (nested loops for enumeration, legacy data when the hierarchy needs to change, etc.).

    On a second thought, maybe you should define a person class

    class Person(object):
        gender = "Male"
        group = "Student"
        id = 123
        Name = "John Doe"
    

    then use a list of all persons and filter with e.g.

    male_students = [s for s in  ALL_PERSONS where s.gender=="Male" and s.group="Student"]
    

    ... for <= 10000 students you should be fine performancewise.

提交回复
热议问题