Home > Mobile >  Change multiple values in a dictionary based on current values
Change multiple values in a dictionary based on current values

Time:11-13

I have a dictionary which I have created from a text file (this works), however I need (key = word, value = category for the word). I have searched for Google and my "Python for Dummies" book for the last 40 minutes and am finding nothing about how to choose one of the categories which are in the values of my dictionary and change all of them to a new value (same dictionary, not create a new one).

Example of data:

Blue colour
Tomato food
Television object

(with blue, tomato and television being the keys, and colour food and object being the values)

Let's say I want to change colour to 1, food to 2 and object to 3 in my dictionary, i.e.:

Blue 1
Tomato 2
Television 3

These aren't the only entries in my dictionary, and so it needs to be something that changes all values of a certain type in one hit.

Is there a way to use a for loop with an if elif loop nested inside to achieve this?

for value in objects.values():
    if value = "colour"
    .............

Or am I totally losing the idea of what I need to do?

CodePudding user response:

You could do it like this:

D = {
    'Blue': 'colour',
    'Tomato': 'food',
    'Television': 'object',
    'Banana': 'fruit',
    'Red': 'colour'
}
VALUEMAP = {
    'colour': 1,
    'food': 2,
    'object': 3
}

for k, v in D.items():
    D[k] = VALUEMAP.get(v, v)

print(D)

{'Blue': 1, 'Tomato': 2, 'Television': 3, 'Banana': 'fruit', 'Red': 1}

Note that the value for Banana is not modified because there's no corresponding entry in the value map

CodePudding user response:

You need to create a count for each unique item you encounter. And then store it in a dictionary. And from that dictionary you can create the final output.

objects = {
        "Blue": "colour",
        "Tomato": "food",
        "Television": "object"
}
unique_objects = {}
unique_objects_count = 0

for value in objects.values():
        if value not in unique_objects:
                unique_objects_count  = 1
                unique_objects[value] = unique_objects_count
for key, value in objects.items():
        objects[key] = unique_objects[value]
print(objects)

OUTPUT

{'Blue': 1, 'Tomato': 2, 'Television': 3}
  • Related