相关疑难解决方法(0)

为什么Python字典不能在此脚本中独立处理密钥?

我期待我的挫败感被一些启示所覆盖 - 这是一个用于演示问题的脚本的最小版本:

首先我创建一个字典:

dic  = {
    'foo':{}, 
    'bar':{}
    }
Run Code Online (Sandbox Code Playgroud)

然后我们实例化一个模板字典,可以迭代地附加到以下键dic:

appendic= {  
    'is':'',       #  '' is a terminal value to be replaced later
}
Run Code Online (Sandbox Code Playgroud)

所以这里我们附加appendic到以下每个键dic:

dic['foo'] = appendic
dic['bar'] = appendic
Run Code Online (Sandbox Code Playgroud)

现在我们用有意义的东西替换终端值'':

dic['foo']['is'] = 'foo'
dic['bar']['is'] = 'bar' 
Run Code Online (Sandbox Code Playgroud)

在这一点上,我的直觉告诉我,如果我们打电话:

print(dic['foo']['is']) 我们得到 'foo'

但是,相反,Python会回归'bar'到我没有训练的头脑,这是违反直觉的.

问题:

  • 如何告诉Python保持dic的密钥独立?
  • 为什么这是默认行为?这有什么用例?

python dictionary key key-value python-2.6

0
推荐指数
1
解决办法
498
查看次数

“Python 从不隐式复制对象”是真的吗?

我在这个问题的一个答案中找到了这个说法。

这是什么意思?如果语句是“Python 从不隐式复制字典对象”,我不会有问题。我相信元组、列表、集合等在 python 中被认为是“对象”,但问题中描述的字典问题不会出现在它们身上。

python dictionary object

0
推荐指数
1
解决办法
183
查看次数

如何迭代更新字典的值并将每个表示形式添加到列表中

当我在循环中更新字典的值时,它也会更改列表中已有的字典的值。

我已经在Python 3.7中尝试了以下代码

d = {"name": "v0"}
a = []
b = ["v1", "v2", "v3"]
for i in b:
    d["name"] = i
    a.append(d)
print(a)
Run Code Online (Sandbox Code Playgroud)

我希望它会在循环中更改字典,并将每个表示形式添加到列表中。但是,它将相同的值添加到列表中。

python python-3.x

0
推荐指数
1
解决办法
50
查看次数

如何正确更新dict中的dict?(Python)

我有以下代码:

some = {}
stat = {'matches_played': 0, 'won': 0, 'draws': 0, 'loss': 0, 'points': 0}
some = {'Arsenal': stat}
some.update({'Chelsea': stat})
some['Arsenal']['won'] += 1
some['Chelsea']['loss'] += 1
print(some)
Run Code Online (Sandbox Code Playgroud)

结果是:

{'Arsenal': {'matches_played': 0, 'won': 1, 'draws': 0, 'loss': 1, 'points': 0}, 
'Chelsea': {'matches_played': 0, 'won': 1, 'draws': 0, 'loss': 1, 'points': 0}}
Run Code Online (Sandbox Code Playgroud)

但是我需要

{'Arsenal': {'matches_played': 0, 'won': 1, 'draws': 0, 'loss': 0, 'points': 0}, 
'Chelsea': {'matches_played': 0, 'won': 0, 'draws': 0, 'loss': 1, 'points': 0}}
Run Code Online (Sandbox Code Playgroud)

您能解释一下为什么会发生这种情况吗?

python

0
推荐指数
1
解决办法
72
查看次数

如何确保字典中的键(或值)具有指定的数据类型?

我的Python程序使用字典,并且有大量的“if”语句只是为了检查检索到的值的类型。

我想避免这种情况,而是以更编程正确的方式进行。

这是一个例子:

# golddb should only contain str keys and int values
golddb = dict()

def gainGold(playername):
  global golddb
  golddb[playername] += 1  # error may happen if I try to += a non-int type
  golddb[playername] = "hello"  # I want python to give an error when I try to assign a str to be a value in the dict
Run Code Online (Sandbox Code Playgroud)

python dictionary types

-1
推荐指数
1
解决办法
6031
查看次数

标签 统计

python ×5

dictionary ×3

key ×1

key-value ×1

object ×1

python-2.6 ×1

python-3.x ×1

types ×1