简体   繁体   中英

Operations on dictionary values have no output

I want to loop through the values of my dictionary and apply simple operations on it. These two SO articles unfortunately did not help me ( Perform an operation on each dictionary value , Perform operation on some not all dictionary values )

My dictionary contains the following data:

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']}

My final objective is to set a label on the key based on the value it contains. For example, 'a' would be 'Workflow 2' because it has the value "Manager". But first I just want to ensure that I can run an operation based on the dictionary values.

My code is:

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

My previous attempts included:

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

Error message:

Traceback (most recent call last): File "C:/Users/.PyCharmCE2018.2/config/scratches/UserAR2-extract.py", line 28, in if key.values() == "Manager": AttributeError: 'str' object has no attribute 'values'

For the code:

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

I do not get any output.

How can I apply operations on dictionary values ?

Looks like your problem is that you want to print if Manager is in the list of values. You just need to change your check from equality (which only occurs if the value is "Manager" alone, not in a list ) to containment:

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

I think this achieves what you are looking for.

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)

Your best bet is to create a copy of the dict and iterate over that as changing values or keys while iterating over them is bad practice. Also it's bad to use dict as a name for an object as it's a built-in method in 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

After this is ran you should end up with:

data = {
    'Workflow 2': "Manager",
    'b': "Automatic",
    'c': "Group"
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM