字典值的运算没有输出

时间:2018-12-17 21:30:40

标签: python python-3.x list dictionary

我想遍历字典的值并对其进行简单的操作。不幸的是,这两篇SO文章对我没有帮助(Perform an operation on each dictionary valuePerform operation on some not all dictionary values

我的词典包含以下数据:

dict = {'WF:ACAA-CR (auto)': ['Manager', 'Access Responsible', 'Automatic'],
        'WF:ACAA-CR-AccResp (auto)': ['Manager', 'Access Responsible', 'Automatic'], 
        'WF:ACAA-CR-IT-AccResp[AUTO]': ['Group', 'Access Responsible', 'Automatic']}

我的最终目标是根据密钥包含的值在密钥上设置标签。例如,“ a”将是“工作流2”,因为它的值为“ Manager”。 但是首先,我只想确保可以根据字典值运行操作。

我的代码是:

for key, values in dict.items():
    if values == "Manager":
        print(key)

我以前的尝试包括:

if key.values() == 'Manager':
    print(key)

错误消息:

  

回溯(最近通话最近):     在第28行的文件“ C:/Users/.PyCharmCE2018.2/config/scratches/UserAR2-extract.py”       如果key.values()==“经理”:   AttributeError:“ str”对象没有属性“ values”

对于代码:

for key in dict.values():
    if key == "Manager":
        print(key)

我没有任何输出。

如何对字典应用操作?

3 个答案:

答案 0 :(得分:2)

看起来您的问题是,如果10在值print中,您想Manager。您只需要将检查从相等性更改(仅当值是list而不是"Manager"时才发生),将其更改为包含:

list

答案 1 :(得分:2)

我认为这可以满足您的需求。

myDict = {'a': "Manager", 'b': "Automatic", 'c': "Group"}

for myKey, myValue in myDict.items():
    if myValue == "Manager":
        print(myKey, myValue)
        myDict.update({myKey: 'Workflow 2'})

print(myDict)

答案 2 :(得分:0)

您最好的选择是创建字典的副本,并在其上进行迭代,因为在迭代它们时更改值或键是不道德的做法。同样,使用dict作为对象的名称也是很糟糕的,因为它是python中的内置方法

from copy import copy

data = {'a': "Manager", 'b': "Automatic", 'c': "Group"}
data_copy = copy(data)

#Now we can iterate over the copy and change the data in our original
for key, value in data_copy.items():
    if value == "Manager":
        data["Workflow 2"] = data.pop[key]
    #and so on

运行之后,您应该得到以下结果:

data = {
    'Workflow 2': "Manager",
    'b': "Automatic",
    'c': "Group"
}
相关问题