Python Forum
Help: for loop with dictionary and nested lists
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Help: for loop with dictionary and nested lists
#1
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'}
Reply
#2
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.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  need to compare 2 values in a nested dictionary jss 2 797 Nov-30-2023, 03:17 PM
Last Post: Pedroski55
  List all possibilities of a nested-list by flattened lists sparkt 1 878 Feb-23-2023, 02:21 PM
Last Post: sparkt
  Big O runtime nested for loop and append yarinsh 4 1,331 Dec-31-2022, 11:50 PM
Last Post: stevendaprano
  Nested for loops - help with iterating a variable outside of the main loop dm222 4 1,532 Aug-17-2022, 10:17 PM
Last Post: deanhystad
  For Loop and Use of Brackets to Modify Dictionary in Tic-Tac-Toe Game new_coder_231013 7 2,168 Dec-28-2021, 11:32 AM
Last Post: new_coder_231013
  Nested dictionary acting strange Pedroski55 2 2,054 May-13-2021, 10:37 PM
Last Post: Pedroski55
  format the output from a nested dictionary. nostradamus64 9 4,424 May-03-2021, 04:45 PM
Last Post: nostradamus64
Lightbulb Python Nested Dictionary michaelserra 2 2,560 Apr-18-2021, 07:54 AM
Last Post: michaelserra
  Adding to the dictionary inside the for-loop - weird behaviour InputOutput007 5 2,651 Jan-21-2021, 02:21 PM
Last Post: InputOutput007
  How do I add another loop to my nested loop greenpine 11 4,440 Jan-12-2021, 04:41 PM
Last Post: greenpine

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020