Home > OS >  How do I zip fields of a dictionary to iterate through their contents concurrently
How do I zip fields of a dictionary to iterate through their contents concurrently

Time:03-23

I have a dictionary of lists: eg

>>> test_dict = {"numbers":[1,2,3],"letters":['a','b','c']}

I want to zip up each field so that I can loop through all of the fields concurrently. I can do this manually like this

>>> for number,letter in zip(test_dict["numbers"],test_dict["letters"]):
>>>    print(f"number {number}, letter {letter}")

number 1, letter a
number 2, letter b
number 3, letter c

Is there any way to do this better without specifying the name of the fields in the zip() command?

CodePudding user response:

Simply use zip(*test_dict.values()).

CodePudding user response:

Just use a double for loop:

test_dict = {"numbers":[1,2,3],"letters":['a','b','c'],"big letters":["A","B","C"]}
all_rows = {}
for names, items in test_dict.items():
    for idx, values in enumerate(items):
        all_rows[idx] = all_rows.get(idx,[])   [f"{names}: {values}"]

for row in all_rows.values():
    print(*row,sep=", ")

results:

numbers: 1, letters: a, big letters: A
numbers: 2, letters: b, big letters: B
numbers: 3, letters: c, big letters: C

The benefit of this is that you can put values of different length together

test_dict = {"numbers":    [ 1,  2,  3,  4,  5],
             "letters":    ['a','b','c'],
             "big letters":["A","B","C","D"]}

results:

numbers: 1, letters: a, big letters: A
numbers: 2, letters: b, big letters: B
numbers: 3, letters: c, big letters: C
numbers: 4, big letters: D
numbers: 5
  • Related