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


Messages In This Thread
Help: for loop with dictionary and nested lists - by mart79 - Apr-12-2020, 12:51 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
Question Using Lists as Dictionary Values bfallert 8 354 Apr-21-2024, 06:55 AM
Last Post: Pedroski55
  need to compare 2 values in a nested dictionary jss 2 880 Nov-30-2023, 03:17 PM
Last Post: Pedroski55
  List all possibilities of a nested-list by flattened lists sparkt 1 927 Feb-23-2023, 02:21 PM
Last Post: sparkt
  Big O runtime nested for loop and append yarinsh 4 1,396 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,605 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,278 Dec-28-2021, 11:32 AM
Last Post: new_coder_231013
  Nested dictionary acting strange Pedroski55 2 2,122 May-13-2021, 10:37 PM
Last Post: Pedroski55
  format the output from a nested dictionary. nostradamus64 9 4,601 May-03-2021, 04:45 PM
Last Post: nostradamus64
Lightbulb Python Nested Dictionary michaelserra 2 2,626 Apr-18-2021, 07:54 AM
Last Post: michaelserra
  Adding to the dictionary inside the for-loop - weird behaviour InputOutput007 5 2,726 Jan-21-2021, 02:21 PM
Last Post: InputOutput007

Forum Jump:

User Panel Messages

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