Home > Enterprise >  How to print values from dictionary in pairs opposite each other
How to print values from dictionary in pairs opposite each other

Time:10-18

For example, this code:

data = {"Name": "salat "
, "Ingredient 1": "salad ", "Number of in1": 60
, "Ingredient 2": "salt ", "Number of in2": 19
, "Ingredient 3": "oil ", "Number of in3": 20
, "Ingredient 4": "cheese ", "Number of in4": 50
, "Ingredient 5": "pepper", "Number of in5": 10
}
for key in data:
    print(data[key])

prints:

salat
salad
60
salt 
19
oil 
20
cheese 
50
pepper
10

but I want:

salat 
salad 60
salt 19
oil 20
cheese 50
pepper 10

How can I get this?

CodePudding user response:

Assuming the dictionary is always sorted this way, you could check if the item if even or odd and change the print end value:

for i,v in enumerate(data.values()):
    print(v, end=' ' if i%2 else '\n')

output:

salat 
salad  60
salt  19
oil  20
cheese  50
pepper 10
  • Related