0

I have dict which got list, what I want is to display list elements in one line.

My dict

data = {'id':[1,2], 'name':['foo','bar'], 'type':['x','y']}

Expected output

   name is foo and id is 1
   name is bar and id is 2

My code

>>> data = {'id':[1,2], 'name':['foo','bar'], 'type':['x','y']}
>>> for key, value in data.items():
...     print(value)
... 
['foo', 'bar']
['x', 'y']
[1, 2]
>>> 
Mark Rotteveel
  • 90,369
  • 161
  • 124
  • 175
harrytrace
  • 21
  • 3
  • Does this answer your question? [How to iterate through two lists in parallel?](https://stackoverflow.com/questions/1663807/how-to-iterate-through-two-lists-in-parallel) – Tomerikoo Mar 19 '21 at 12:42
  • Your code just prints the `value`, and that is what you got. You say you expect `name is foo and id is 1` but your code does not have the strings "name is", nor "and id is" – phzx_munki Mar 19 '21 at 22:48

1 Answers1

2

You can use zip() as:

for name, idx in zip(data['name'], data['id']):
    print(f"name is {name} and id is {idx}")

Use format() if you are using python version lower than 3.6:

for name, idx in zip(data['name'], data['id']):
    print("name is {0} and id is {1}".format(name, idx))
Krishna Chaurasia
  • 8,130
  • 6
  • 18
  • 31