-2

I'm new to coding and I'm trying to make a program that will take 2 vegetables from a list and print them one after another, then go to the next one and print it again. So if I have something like this:

vegetables = { "tomato": "red", "cucumber": "green", "orange":"orange", "lemon": "yellow" }

How do I make it say in console:

"tomato": "red", "cucumber": "green"

and after that

"orange":"orange", "lemon": "yellow"

And if it's possible can it say "tomato": "red", "cucumber": "green" twice and after that "orange":"orange", "lemon": "yellow" twice again. And I would love if it worked for many elements because I will have bigger list.

Pranav Hosangadi
  • 23,755
  • 7
  • 44
  • 70
Nice
  • 1
  • 1
    So what have you tried so far? Please update your question with a snippet of code that you tried and did not work as expected. – Bogdan Prădatu Feb 17 '22 at 14:55
  • 1
    Does this answer your question? [What is the most "pythonic" way to iterate over a list in chunks?](https://stackoverflow.com/questions/434287/what-is-the-most-pythonic-way-to-iterate-over-a-list-in-chunks) Where the *list* is `vegetables.items()` – Tomerikoo Feb 17 '22 at 16:36

1 Answers1

-1

A dictionary is organised with keys/values:

my_dictionnay = { my_key : myvalue }

(You can add any keys/values as long as his keys are different.)

So you can use keys() & values() methods on the vegetables dictionary.

Those methods returns each keys and values from your dictionary.

Example: get each values from your dictionary:

vegetables = { "tomato": "red", "cucumber": "green", "orange":"orange", "lemon": "yellow" }

for colour in vegetables.values():
    print(colour)

You can do the same for the keys changing vegetables.values() to vegetables.keys()

Now let's get our keys/values in a single for loop;

vegetables = { "tomato": "red", "cucumber": "green", "orange":"orange", "lemon": "yellow" }

for vegetable, colour in vegetables.items():
    print(vegetable, ":", colour)

If you want more details on dictionary you can read this.

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Paul
  • 388
  • 1
  • 5
  • 11
  • 2
    1. This doesn't answer the question, which is how to print in chunks of 2 elements. 2. Why `zip(d.keys(), d.values()` when `d.items()` exists? – Pranav Hosangadi Feb 17 '22 at 16:35
  • 1
    Also you do `for vegetable, colour in ...:` but then `print(key, ':', value)`. Both `key` and `value` are not defined... – Tomerikoo Feb 17 '22 at 16:37