Store additional keys in dict of dicts

荒凉一梦 提交于 2019-12-12 01:54:54

问题


I am trying to figure out how can we add additional information to python dictionary.

For example as per standard way, we can have ["python":14, "Programming":15]. Now I may want to store it as ["d1":"python":14, "d1":"Programming":15] as 1 set.

How can we achieve this?


回答1:


store dicts of dicts using d1, d2,d3 etc.. as the keys:

d={"d1":{"python":14,"Programming":15},"d2":{"python":14,"Programming":15}}

Just access each sub dict to get what you need:

In [11]: d = {"d1":{"python":14,"Programming":15},"d2":{"python":14,"Programming":15}}    
In [12]: d["d1"]
Out[12]: {'Programming': 15, 'python': 14} # d1's value is a dict
In [13]: d["d2"]
Out[13]: {'Programming': 15, 'python': 14} # d2's value is a dict
In [14]: d["d2"]["python"]
Out[14]: 14    
In [14]: d["d2"]["Programming"]
Out[14]: 15

You can also nest further as per your comment:

In [16]: d={"p1": {"d1":{"python":14,"Programming":15}}, "p2": {"d1":{"python":14,"Programming":15}} }

In [17]: d["p2"]["d1"]
Out[17]: {'Programming': 15, 'python': 14}
In [18]: d["p2"]["d1"]["python"]
Out[18]: 14



回答2:


If I understand your question correctly, you want to be able to have multiple different keys map to the same value, so that

    my_dict["d1"] = 14 
    my_dict["python"] = 14

Dict objects support that easily, you just need to define

    my_dict = {"d1":14,"python":14,"d2":15}

If on the other hand you want a single key to be able to map to multiple values, you could try Padraic's answer or you could try

    my_dict = {"d1":("python",14)}

though that might not be quite what you're looking for if you want a truly nested data structure.



来源:https://stackoverflow.com/questions/28518331/store-additional-keys-in-dict-of-dicts

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!