将附加的键存储在命令中 [英] Store additional keys in dict of dicts

查看:106
本文介绍了将附加的键存储在命令中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



例如,按照标准方式,我们可以使用 [python:14,编程:15]
现在我可能想把它存储为 [d1:python:14,d1:编程:15] 为1集。



我们如何实现这一点?

解决方案

使用d1,d2,d3等作为键:

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

只需访问每个子dict来获取所需的内容:

 在[11]中:d = {d1 :{python:14,编程:15},d2:{python:14,编程:15}} 
在[12]中:d [d1]
输出[12]:{'编程':15,'python':14}#d1的值是一个dict
在[13]中:d [d2]
输出[13] :{'编程':15,'python':14}#d2的值是一个dict
在[14]中:d [d2] [python]
Out [14]:14
在[14]中:d [d2] [编程]
出[14]:15

您还可以根据您的意见进一步嵌套:

 在[16]中:d = {p1:{d1:{python:14,编程:15}},p2:{d1:{python:14,编程:15}}} 

在[17]中: d [p2] [d1]
输出[17]:{'编程':15,'python':14}
在[18]中:d [p2] [ d1] [python]
Out [18]:14


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?

解决方案

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

这篇关于将附加的键存储在命令中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆