如何引用dict对象? [英] How to reference a dict object?

查看:39
本文介绍了如何引用dict对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 Python dict 对象 d.d = {'a': 1, 'b': 2, 'c': 3}.我的问题真的很简单.我想引用一个变量到 d 的元素.例如,类似于:

输入[1]:p = d['a']>>>p = 1在[2]:p = 2在[3]:d>>>d = {'a':2,'b':2,'c':3}

这可能吗?但据我所知 dict 对象是可变的.

解决方案

正如其他人所指出的,这在 Python 中是不可能的,它没有 C++ 风格的引用.你能得到的最接近的是,如果你的字典值是可变的,那么你可以在外面改变它,它会反映在字典内部(因为你正在改变与存储在字典中的对象相同的对象).这是一个简单的演示:

<预><代码>>>>d = {'1': [1, 2, 3] }>>>d{'1': [1, 2, 3]}>>>x = d['1']>>>x.append(4)>>>d{'1': [1, 2, 3, 4]}

但总的来说,这是一个糟糕的模式.如果可以避免,请不要这样做,这会使您很难推理字典中的内容.如果你想改变那里的东西,把钥匙传过来.那就是你想要的.

I have a Python dict object d. d = {'a': 1, 'b': 2, 'c': 3}. My problem is really simple. I want to reference a variable to the elements of d. For example, something like:

In[1]: p = d['a']
>>> p = 1
In[2]: p = 2
In[3]: d
>>> d = {'a': 2, 'b': 2, 'c': 3}

Is that even possible? But as far as I know dict objects are mutable.

解决方案

As others have pointed out, this is not really possible in Python, it doesn't have C++ style references. The closest you can get is if your dictionary value is mutable, then you can mutate it outside and it will be reflected inside the dictionary (because you're mutating the same object as the object stored in the dictionary). This is a simple demonstration:

>>> d = {'1': [1, 2, 3] }
>>> d
{'1': [1, 2, 3]}
>>> x = d['1']
>>> x.append(4)
>>> d
{'1': [1, 2, 3, 4]}

But in general, this is a bad pattern. Don't do this if you can avoid it, it makes it really hard to reason about what's inside the dictionary. If you wanna change something in there, pass the key around. That's what you want.

这篇关于如何引用dict对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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