Home > Back-end >  How to iterate over list values in dictionary per key?
How to iterate over list values in dictionary per key?

Time:07-07

Here's my code:

msgs = {}
msgs['ch1']=['testmsg1', 'testmsg2']
msgs['ch2']=['testmsg3','testmsg4','testmsg5']

counter = 0
for key, val in msgs.items():
    while counter < len(val):
        print(key, val[counter])
        counter  = 1

Here's the output I'm currently getting:

ch1 testmsg1
ch1 testmsg2
ch2 testmsg5

And here's the output I'd like:

ch1 testmsg1
ch1 testmsg2
ch2 testmsg3
ch2 testmsg4
ch2 testmsg5

Thanks in advance for your help, I'm still learning and would benefit from an explanation!

CodePudding user response:

It looks like you want to get all the values in the list. As @Jnevill said, you could fix how you're using the counter, but since you know how many objects are in the list you would be better to use a for loop instead of a while loop. So

msgs = {}
msgs['ch1']=['testmsg1', 'testmsg2']
msgs['ch2']=['testmsg3','testmsg4','testmsg5']

for key, val in msgs.items():
    for element in val:
        print(key, element)

CodePudding user response:

If you want to use the while loop here, you need to move your counter variable inside the for loop like such:

msgs = {}
msgs['ch1']=['testmsg1', 'testmsg2']
msgs['ch2']=['testmsg3','testmsg4','testmsg5']

for key, val in msgs.items():
    counter = 0
    while counter < len(val):
        print(key, val[counter])
        counter  = 1

This way, your counter will reset to 0 when it goes to the next key in the dictionary. Previously, the counter is 0 at testmsg1, 1 at testmsg2, but when it encounters the key ch2, the counter is now at 2, and only prints testmsg5.

CodePudding user response:

Can you do the following, or am I missing something?

msgs = {}
msgs['ch1']=['testmsg1', 'testmsg2']
msgs['ch2']=['testmsg3','testmsg4','testmsg5']

for key in msgs:
    for val in msgs[key]:
        print(key, val)

CodePudding user response:

In a single iteration:

  • make a string template
  • use map to apply the template to each value in the list
  • use print with separator \n
for k, vs in msgs.items():
    template = k   ' {}'
    print(*map(template.format, vs), sep='\n')

Or with a simple 2-lines way using str.join:

for k, vs in msgs.items():
    print('\n'.join(f'{k} {v}' for v in vs))
  • Related