Monday, February 3, 2025

Python For Loops with Complex Values

 I found myself needing to loop through a dictionary that looked like this:

data = {
    'key1': ['id1', 'subnet1'],
    'key2': ['id2', 'subnet2'],
    'key3': ['id3', 'subnet3']
}

Normally, I'd do this:

for key, v in data.items():
  id = v[0]
  subnet = v[1]
  print(f"{key}: {id} {subnet}")

But today I figured I'd let AI suggest an efficiency and it came through. Instead of the above, I can do just this:

for key, (id, subnet) in data.items():
  print(f"{key}: {id} {subnet}")


No comments:

Post a Comment