python - 在Python中解压字典并获取值

标签 python dictionary iterable-unpacking

我有这本字典,我正在尝试提取值

dict = {'distances': array([ 870.99793539]), 'labels': array([2])}

我尝试使用

self.printit(**dict)

def printit(distances,labels):         
    print distances
    print labels

但我收到错误

TypeError: printit() got multiple values for keyword argument 'distances'

最佳答案

为什么你会收到 TypeError:

当您使用 self.printit(**somedict) 调用方法时,传递给函数 printit 的第一个参数是 self。所以如果你定义

def printit(distances, labels):

距离设置为self。由于 somedict 包含一个名为 distances 的键,因此 distances 关键字被提供了两次。 这就是引发 TypeError 的原因。


如何修复它:

你的函数

def printit(distances,lables):  

使用名为lables的变量,但字典有一个拼写为labels的键。您可能希望将 lables 更改为 labels


self 添加为 printit 的第一个参数。

def printit(self, distances, labels): 

调用第一个参数 self 只是一种约定 - 您可以将其称为其他名称(尽管不推荐) - 但您绝对需要将调用后出现一些变量名称

self.printit(...) 将调用 printit(self, ...)


例如,

import numpy as np
class Foo(object):
    def printit(self, distances, labels): 
            print distances
            print labels

somedict = {'distances': np.array([ 870.99793539]), 'labels': np.array([2])}
self = Foo()
self.printit(**somedict)

打印

[ 870.99793539]
[2]

关于python - 在Python中解压字典并获取值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17506261/

相关文章:

python - 使用 --auto 更改带有 django+south 迁移的表的编码

javascript - 使用 React 和 Bootstrap 通过数组进行映射

python - 输入 : type hinting when function returns tuple with unpacked list

Python glob——从列表中获取最新文件

python - Objective-C/cocoa相当于Python的os.path.split()获取目录名和文件名

python - 给定一组字符串,创建一个字典字典,使用它们作为具有默认值的条目的键

python - 从 Python2 到 Python3 的这种解包行为的变化是什么?

Python 函数返回无序列表对象

python - 在django模型中使用python super 函数

python - 如何访问字典中所有键的值?