相关疑难解决方法(0)

更简单的方法来创建单独变量的字典?

我希望能够将变量的名称作为字符串获取,但我不知道Python是否具有那么多的内省功能.就像是:

>>> print(my_var.__name__)
'my_var'
Run Code Online (Sandbox Code Playgroud)

我想这样做因为我有一堆vars我想变成一本字典,如:

bar = True
foo = False
>>> my_dict = dict(bar=bar, foo=foo)
>>> print my_dict 
{'foo': False, 'bar': True}
Run Code Online (Sandbox Code Playgroud)

但我想要比这更自动的东西.

Python中有locals()vars(),所以我想有一种方法.

python string variables

218
推荐指数
11
解决办法
23万
查看次数

Python创建列表字典

我想创建一个值为列表的字典.例如:

{
  1: ['1'],
  2: ['1','2'],
  3: ['2']
}
Run Code Online (Sandbox Code Playgroud)

如果我做:

d = dict()
a = ['1', '2']
for i in a:
    for j in range(int(i), int(i) + 2): 
        d[j].append(i)
Run Code Online (Sandbox Code Playgroud)

我得到一个KeyError,因为d [...]不是一个列表.在这种情况下,我可以在分配初始化字典后添加以下代码.

for x in range(1, 4):
    d[x] = list()
Run Code Online (Sandbox Code Playgroud)

有一个更好的方法吗?让我们说在我进入第二个for循环之前,我不知道我需要的密钥.例如:

class relation:
    scope_list = list()
...
d = dict()
for relation in relation_list:
    for scope_item in relation.scope_list:
        d[scope_item].append(relation)
Run Code Online (Sandbox Code Playgroud)

然后将替代另一种选择

d[scope_item].append(relation)
Run Code Online (Sandbox Code Playgroud)

if d.has_key(scope_item):
    d[scope_item].append(relation)
else:
    d[scope_item] = [relation,]
Run Code Online (Sandbox Code Playgroud)

处理这个问题的最佳方法是什么?理想情况下,追加将"正常工作".有没有办法表达我想要一个空列表字典,即使我在第一次创建列表时不知道每个键?

python dictionary

206
推荐指数
3
解决办法
49万
查看次数

标签 统计

python ×2

dictionary ×1

string ×1

variables ×1