Python Forum

Full Version: Help: for loop with dictionary and nested lists
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi all,

Can you help me with the following double for loop, writing it more cleanly and make it work for 'lc3'

old = 'car'
new = 'scooter'

loadcases = {'lc1': [['car', 'red', '10'], ['train', 'blue', '20'], ['airplane', 'gray', '300']], 'lc2': [['bike', 'red', '10'], ['train', 'blue', '20'], ['car', 'gray', '300']], 'lc3': 'car'}

# this works for lc1 and lc2 but not for lc3, how can I incorporate this too?
for lc in loadcases:
    for element in loadcases[lc]:
        if element[0] == old:
           element[0] = new
The output needs to be as follows:
Output:
{'lc1': [['scooter', 'red', '10'], ['train', 'blue', '20'], ['airplane', 'gray', '300']], 'lc2': [['bike', 'red', '10'], ['train', 'blue', '20'], ['scooter', 'gray', '300']], 'lc3': 'scooter'}
This is what happens when you use different types for values. lc1 and lc2 are lists of lists of strings, and lc3's value is a string. It is best to avoid mixed types like this if you can. If you cannot prevent mixed types, then you will need to determine the type of the value (use the type() function), and then act accordingly.