Python:如何提取字典条目的变量名?

发布于 2024-07-15 22:11:05 字数 1806 浏览 5 评论 0原文

我想知道如何查找字典元素的变量名称:

例如:

    >>>dict1={}
    >>>dict2={}

    >>>dict1['0001']='0002'
    >>>dict2['nth_dict_item']=dict1
    >>>print dict2
    {'nth_dict_item': {'0001': '0002'}}
    >>>print dict2['nth_dict_item']
    {'001': '002'}

我怎样才能让它告诉我 dict2['nth_dict_item'] 是或正在引用“dict1”? 我想要它引用的数据结构的名称,而不是数据本身。

如果我将 id(dict1) 的输出与 id(dict2['nth_dict_item']) 进行比较,我可以发现它们是相同的。

但是我怎样才能将该 id 转回变量名呢? 有没有更直接/更干净的方法来获取我想知道的信息?

我确信我只是忽略了一个让我的生活变得轻松的函数,但我对 Python 还很陌生:)

感谢任何帮助,谢谢!

相关


更新:这就是原因我希望这个能起作用:

我正在尝试制作一个使用类似于数据库的字典的应用程序。 我希望这个伪代码的功能能够发挥作用:

dict_1={}
dict_2={}
dict_3={}

dict_1["FooBar1.avi"]=[movie_duration,movie_type,comments]
dict_2["FooBar2.avi"]=[movie_duration,movie_type,comments]
dict_3["FooBar3.avi"]=[movie_duration,movie_type,comments]

dict_database[SomeUniqueIdentifier1]=dict_1
dict_database[SomeUniqueIdentifier2]=dict_2
dict_database[SomeUniqueIdentifier3]=dict_3

SomeUniqueIdentifier# 将是一个唯一值,我将其用作数据库键/unqiueID 来查找条目。

我希望能够通过以下方式更新 FooBar1.avi 的“评论”字段:

WhichDict= dict_database[SomeUniqueIdentifier1]
WhichDict[WhichDict.keys()[0]][2]='newcomment'

而不必这样做:

dict_database['SomeUniqueIdentifier1'][dict_database['SomeUniqueIdentifier1'].keys()[0]][2]='newcomment'

谢谢大家。 我现在明白我误解了很多基础知识(完全是大脑放屁)。 将返回并修复设计。 谢谢大家!

I'm wondering how I would go about finding the variable name of a dictionary element:

For example:

    >>>dict1={}
    >>>dict2={}

    >>>dict1['0001']='0002'
    >>>dict2['nth_dict_item']=dict1
    >>>print dict2
    {'nth_dict_item': {'0001': '0002'}}
    >>>print dict2['nth_dict_item']
    {'001': '002'}

How can I go about making it tell me that dict2['nth_dict_item'] is or is referencing "dict1" ? I want the name of the data structure it's referencing and not the data itself.

If I compare the output of id(dict1) to id(dict2['nth_dict_item']) I can find they are the same.

But how can I turn that id back into a variable name? Is there a more direct/cleaner method of getting the information that I want to know?

I'm sure I'm just overlooking a function that would make my life easy but I'm pretty new to Python :)

Any help is appreciated, thanks!

Related


Update: Here's why I wanted this to work:

I'm trying to make an app that uses a dictionary kinda like a database. I wanted the functionality of this psuedocode to function:

dict_1={}
dict_2={}
dict_3={}

dict_1["FooBar1.avi"]=[movie_duration,movie_type,comments]
dict_2["FooBar2.avi"]=[movie_duration,movie_type,comments]
dict_3["FooBar3.avi"]=[movie_duration,movie_type,comments]

dict_database[SomeUniqueIdentifier1]=dict_1
dict_database[SomeUniqueIdentifier2]=dict_2
dict_database[SomeUniqueIdentifier3]=dict_3

SomeUniqueIdentifier# would be a unique value that I'm using as a database key/unqiueID to look up entries.

I want to be able to update the "comments" field of FooBar1.avi by:

WhichDict= dict_database[SomeUniqueIdentifier1]
WhichDict[WhichDict.keys()[0]][2]='newcomment'

instead of having to do:

dict_database['SomeUniqueIdentifier1'][dict_database['SomeUniqueIdentifier1'].keys()[0]][2]='newcomment'

Thanks everyone. I now understand I was misunderstanding a LOT of basics (total brain fart). Will go back and fix the design. Thanks to you all!.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(7

渡你暖光 2024-07-22 22:11:05

变量名只是一个名称——就程序而言,它没有真正的含义,除了为程序员提供方便(这在 Python 中并不完全正确,但请耐心等待)。 对于Python解释器而言,名称dict1只是程序员告诉Python查看内存地址0x1234的方式。

此外,将内存地址 (0x1234) 转回变量名称 (dict1) 的想法没有意义,特别是考虑到多个变量名称可以引用同一个对象:

dict1 = {...}
dictCopy = dict1

现在 dictCopydict1 一样是字典的名称 - 它们都引用相同的东西。 如果您要查找的函数已经存在,Python 应该选择哪个名称?

A variable name is just a name--it has no real meaning as far as the program is concerned, except as a convenience to the programmer (this isn't quite true in Python, but bear with me). As far as the Python interpreter is concerned, the name dict1 is just the programmer's way of telling Python to look at memory address 0x1234.

Furthermore, the very idea of turning a memory address (0x1234) back into a variable name (dict1) doesn't make sense, especially considering that more than one variable name can reference the same object:

dict1 = {...}
dictCopy = dict1

Now dictCopy is just as much the name of the dictionary as dict1 is--they both reference the same thing. If the function you're looking for existed, which name should Python choose?

补充一下 zenazn 所说的:

但是我怎样才能将该 id 转回变量名呢?

简短的回答是你并不真正想要。 如果您认为需要这样做,则说明您的程序设计有问题。 如果您更具体地告诉我们您想要解决什么问题,我们可以帮助您找到更好的方法来完成它。

To add what zenazn said:

But how can I turn that id back into a variable name?

The short answer is that you don't want really want to. If you think you need to, there's something very wrong with the design of your program. If you told us more concretely what problem you were trying to solve, we could help you work out a better way to accomplish it.

德意的啸 2024-07-22 22:11:05

简单的答案:而不是

WhichDict[WhichDict.keys()[0]][2]='newcomment'

使用:

WhichDict.values()[0][2]='newcomment'

但是使用字典来表示单个电影是非常不合适的。 为什么不使用类来代替呢?

class Movie(object):
    def __init__(self, filename, movie_duration, movie_type, comments):
        self.filename = filename
        self.movie_duration = movie_duration
        self.movie_type = movie_type
        self.comments = comments

database = dict()
database['unique_id_1'] = Movie("FooBar1.avi", duration, type, comments)
# ...

some_movie = database[some_id]
some_movie.comment = 'newcomment'

The trivial answer: instead of

WhichDict[WhichDict.keys()[0]][2]='newcomment'

use:

WhichDict.values()[0][2]='newcomment'

But using a dictionary to represent a single movie is grossly inappropriate. Why not use a class instead?

class Movie(object):
    def __init__(self, filename, movie_duration, movie_type, comments):
        self.filename = filename
        self.movie_duration = movie_duration
        self.movie_type = movie_type
        self.comments = comments

database = dict()
database['unique_id_1'] = Movie("FooBar1.avi", duration, type, comments)
# ...

some_movie = database[some_id]
some_movie.comment = 'newcomment'
戒ㄋ 2024-07-22 22:11:05

现在,对于每部电影,您正在做的事情是:

dict_n = {}
dict_n["000n"] = [movie_duration,movie_type,comments]

每个字典只有一个条目。 然后,您将多个电影字典存储在一个中央字典中:

dict_database = {}
dict_database["0001"] = dict_1
dict_database["0002"] = dict_2
dict_database["0003"] = dict_3
dict_database["000n"] = dict_n

编辑:这可能就是您的想法。

对于每部电影,都有一个从属性名称到值的字典。

movie_n = {}
movie_n["movie_duration"] = 333
movie_n["movie_type"] = "Fantasy"
movie_n["comments"] = ""

然后 movies["any_file.avi"] 会给你这个字典。 要将电影添加到目录中,然后添加注释,请输入:

movies["any_file.avi"] = movie_n
movies["any_file.avi"]["comments"] = "new comment"

如果您必须在该电影的编号和文件名之间进行选择,我会选择文件名,因为当您实际尝试时它更相关访问电影。 另外,如果有必要,您可以通过 Movies.keys() 或类似的东西枚举您的电影(尽管顺序不正确)。 如果您想同时使用数字和文件名,请将文件名添加为每部电影的另一个键。

movie_n["filename"] = "any_file.avi"

或者

movies["000n"]["filename"] = "any_file.avi"

Right now, for each movie, you're doing:

dict_n = {}
dict_n["000n"] = [movie_duration,movie_type,comments]

with only one entry per dict. Then you're storing multiple movie dicts in a central one:

dict_database = {}
dict_database["0001"] = dict_1
dict_database["0002"] = dict_2
dict_database["0003"] = dict_3
dict_database["000n"] = dict_n

Edit: This is probably what you had in mind.

For each movie, there's a dict going from property names to values.

movie_n = {}
movie_n["movie_duration"] = 333
movie_n["movie_type"] = "Fantasy"
movie_n["comments"] = ""

Then movies["any_file.avi"] gives you that dict. To add the movie to the directory and then add a comment, you enter:

movies["any_file.avi"] = movie_n
movies["any_file.avi"]["comments"] = "new comment"

If you have to choose between the number of that movie and the filename, I'd go with the filename because it's simply more relevant when you're actually trying to access a movie. Plus, if necessary you can enumerate your movies (albeit out of order) through movies.keys() or something similar. If you want to use both a number and the filename, add the filename as another key for each movie.

movie_n["filename"] = "any_file.avi"

or

movies["000n"]["filename"] = "any_file.avi"
浸婚纱 2024-07-22 22:11:05

您需要重新考虑您的设计。

一个快速的技巧是将变量名称实际放入...

dict2['item_n'] = 'dict1'

或者可能使用元组..

dict2['item_n'] = ('dict1', dict1)

有一个名为 locals() 的函数,它提供了局部变量名称的字典,也许你可以考虑它当你重新思考你的设计时。

在这里,看看 locals() 是如何工作的:

>>> x = 10
>>> y = 20
>>> c = "kmf"
>>> olk = 12
>>> km = (1,6,"r",x)
>>> from pprint import pprint
>>> pprint( locals() )
{'__builtins__': <module '__builtin__' (built-in)>,
 '__doc__': None,
 '__name__': '__main__',
 'c': 'kmf',
 'km': (1, 6, 'r', 10),
 'olk': 12,
 'pprint': <function pprint at 0x016A0EB0>,
 'x': 10,
 'y': 20}

UPDATE

我希望能够通过以下方式更新 FooBar1.avi 的“评论”字段:

WhichDict= dict_database[SomeUniqueIdentifier1]
WhichDict[WhichDict.keys()[0]][2]='newcomment'

嗯,这很简单

dict_databse[identifier][2] = the_new_comment

You need to rethink your design.

A quick hack would be to actually put the variable name in ...

dict2['item_n'] = 'dict1'

or maybe use a tuple ..

dict2['item_n'] = ('dict1', dict1)

There's a function called locals() which gives a dictionary of local variable names, maybe you can consider it when you rethink about your design.

Here, have a look at how locals() works:

>>> x = 10
>>> y = 20
>>> c = "kmf"
>>> olk = 12
>>> km = (1,6,"r",x)
>>> from pprint import pprint
>>> pprint( locals() )
{'__builtins__': <module '__builtin__' (built-in)>,
 '__doc__': None,
 '__name__': '__main__',
 'c': 'kmf',
 'km': (1, 6, 'r', 10),
 'olk': 12,
 'pprint': <function pprint at 0x016A0EB0>,
 'x': 10,
 'y': 20}

UPDATE

I want to be able to update the "comments" field of FooBar1.avi by:

WhichDict= dict_database[SomeUniqueIdentifier1]
WhichDict[WhichDict.keys()[0]][2]='newcomment'

Well, this is trivial

dict_databse[identifier][2] = the_new_comment

红颜悴 2024-07-22 22:11:05

我怎样才能让它告诉我
dict2['nth_dict_item'] 是或是
引用“dict1”?

>>> print dict2['nth_dict_item'] is dict1
True

How can I go about making it tell me
that dict2['nth_dict_item'] is or is
referencing "dict1" ?

>>> print dict2['nth_dict_item'] is dict1
True
瞎闹 2024-07-22 22:11:05

使用孔雀鱼

from guppy import hpy
h=hpy()
h.iso(dict2['nth_dict_item']).sp

0: h.Root.i0_modules['__main__'].__dict__['dict1']

Use Guppy.

from guppy import hpy
h=hpy()
h.iso(dict2['nth_dict_item']).sp

0: h.Root.i0_modules['__main__'].__dict__['dict1']
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文