Python 获取字典名称
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/25146324/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Get name of dictionary
提问by Gabriel
I find myself needing to iterate over a list made of dictionaries and I need, for every iteration, the name of which dictionary I'm iterating on.
我发现自己需要迭代一个由字典组成的列表,并且每次迭代我都需要我正在迭代的字典的名称。
Here's an MWE (the contents of the dicts are irrelevant for this example) :
这是一个 MWE(字典的内容与此示例无关):
dict1 = {...}
dicta = {...}
dict666 = {...}
dict_list = [dict1, dicta, dict666]
for dc in dict_list:
# Insert command that should replace ???
print 'The name of the dictionary is: ', ???
If I just use dcwhere ???is, it will print the entire contents of the dictionary. How can I get the name of the dictionary being used?
如果我只使用dcwhere ???is,它将打印字典的全部内容。如何获得正在使用的字典的名称?
采纳答案by Adam Smith
Don't use a dict_list, use a dict_dictif you need their names. In reality, though, you should really NOT be doing this. Don't embed meaningful information in variable names. It's tough to get.
不要使用 a dict_list,dict_dict如果您需要他们的名字,请使用 a 。但实际上,您真的不应该这样做。不要在变量名中嵌入有意义的信息。很难得到。
dict_dict = {'dict1':dict1, 'dicta':dicta, 'dict666':dict666}
for name,dict_ in dict_dict.items():
print 'the name of the dictionary is ', name
print 'the dictionary looks like ', dict_
Alternatively make a dict_setand iterate over locals()but this is uglier than sin.
或者 make adict_set并迭代,locals()但这比罪更丑。
dict_set = {dict1,dicta,dict666}
for name,value in locals().items():
if value in dict_set:
print 'the name of the dictionary is ', name
print 'the dictionary looks like ', value
Again: uglier than sin, but it DOES work.
再说一遍:比罪更丑,但它确实有效。
回答by Jeff Tsui
You should also consider adding a "name" key to each dictionary.
您还应该考虑为每个字典添加一个“名称”键。
The names would be:
名称将是:
for dc in dict_list:
# Insert command that should replace ???
print 'The name of the dictionary is: ', dc['name']
回答by martineau
Objects don't have names in Python and multiple names could be assigned to the same object.
对象在 Python 中没有名称,可以为同一个对象分配多个名称。
However, an object-oriented way to do what you want would be to subclass the built-indictdictionary class and add anameproperty to it. Instances of it would behave exactly like normal dictionaries and could be used virtually anywhere a normal one could be.
但是,做您想做的事情的面向对象的方法是将内置dict字典类子类化并name为其添加属性。它的实例的行为与普通词典完全一样,几乎可以在普通词典所在的任何地方使用。
class NamedDict(dict):
def __init__(self, *args, **kwargs):
try:
self._name = kwargs.pop('name')
except KeyError:
raise KeyError('a "name" keyword argument must be supplied')
super(NamedDict, self).__init__(*args, **kwargs)
@classmethod
def fromkeys(cls, name, seq, value=None):
return cls(dict.fromkeys(seq, value), name=name)
@property
def name(self):
return self._name
dict_list = [NamedDict.fromkeys('dict1', range(1,4)),
NamedDict.fromkeys('dicta', range(1,4), 'a'),
NamedDict.fromkeys('dict666', range(1,4), 666)]
for dc in dict_list:
print 'the name of the dictionary is ', dc.name
print 'the dictionary looks like ', dc
Output:
输出:
the name of the dictionary is dict1
the dictionary looks like {1: None, 2: None, 3: None}
the name of the dictionary is dicta
the dictionary looks like {1: 'a', 2: 'a', 3: 'a'}
the name of the dictionary is dict666
the dictionary looks like {1: 666, 2: 666, 3: 666}
回答by SummerEla
The following doesn't work on standard dictionaries, but does work just fine with collections dictionaries and counters:
以下不适用于标准字典,但适用于集合字典和计数器:
from collections import Counter
# instantiate Counter ditionary
test= Counter()
# create an empty name attribute field
test.name = lambda: None
# set the "name" attribute field to "name" = "test"
setattr(test.name, 'name', 'test')
# access the nested name field
print(test.name.name)
It's not the prettiest solution, but it is easy to implement and access.
这不是最漂亮的解决方案,但它易于实施和访问。
回答by Carl Brubaker
Here's my solution for a descriptive error message.
这是我针对描述性错误消息的解决方案。
def dict_key_needed(dictionary,key,msg='dictionary'):
try:
value = dictionary[key]
return value
except KeyError:
raise KeyError(f"{msg} is missing key '{key}'")
回答by Habibur Rahman
If you want to read name and value
如果要读取名称和值
dictionary={"name1":"value1","name2":"value2","name3":"value3","name4":"value4"}
for name,value in dictionary.items():
print(name)
print(value)
If you want to read name only
如果您只想读取名称
dictionary={"name1":"value1","name2":"value2","name3":"value3","name4":"value4"}
for name in dictionary:
print(name)
If you want to read value only
如果您只想读取值
dictionary={"name1":"value1","name2":"value2","name3":"value3","name4":"value4"}
for values in dictionary.values():
print(values)
Here is your answer
这是你的答案
dic1 = {"dic":1}
dic2 = {"dic":2}
dic3 = {"dic":3}
dictionaries = [dic1,dic2,dic3]
for i in range(len(dictionaries)):
my_var_name = [ k for k,v in locals().items() if v == dictionaries[i]][0]
print(my_var_name)

