Python Forum
Help: for loop with dictionary and nested lists - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: Help: for loop with dictionary and nested lists (/thread-25815.html)



Help: for loop with dictionary and nested lists - mart79 - Apr-12-2020

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



RE: Help: for loop with dictionary and nested lists - TomToad - Apr-12-2020

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.