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
Question Using Lists as Dictionary Values bfallert 4 107 40 minutes ago
Last Post: bfallert
  need to compare 2 values in a nested dictionary jss 2 855 Nov-30-2023, 03:17 PM
Last Post: Pedroski55
  List all possibilities of a nested-list by flattened lists sparkt 1 915 Feb-23-2023, 02:21 PM
Last Post: sparkt
  Big O runtime nested for loop and append yarinsh 4 1,387 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,585 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,239 Dec-28-2021, 11:32 AM
Last Post: new_coder_231013
  Nested dictionary acting strange Pedroski55 2 2,087 May-13-2021, 10:37 PM
Last Post: Pedroski55
  format the output from a nested dictionary. nostradamus64 9 4,548 May-03-2021, 04:45 PM
Last Post: nostradamus64
Lightbulb Python Nested Dictionary michaelserra 2 2,597 Apr-18-2021, 07:54 AM
Last Post: michaelserra
  Adding to the dictionary inside the for-loop - weird behaviour InputOutput007 5 2,710 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