Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Optimum solution using for loop

I have a list

items=["apple","carrot","bike","dog"]

The result I want

ordered_items = {"fruit": items[0],"vegetable":items[1],"vehicle":items[2],"animal":items[3]}

print(ordered_items)

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

{
"fruit": "apple","vegetable":"carrot","vehicle":"bike","animal":"dog"
}

Here I have to explicitly mention the index from the list(items) in the resultant dictionary(ordered_items) which is definitely not the right approach when the list(items) gets updated in the future.

Is there any alternative way I can form in key-value pair by using for-loop/count or something?

>Solution :

You can initialize a dict straight from the output of zip like this:

items = ["apple", "carrot", "bike", "dog"]
categories = ["fruit", "vegetable", "vehicle", "animal"]

dict(zip(categories, items))

>>> {'fruit': 'apple', 'vegetable': 'carrot', 'vehicle': 'bike', 'animal': 'dog'}

Explanation

A dict can be instantiated in different ways, one of which is sequence of key-value pairs:

dict([("foo", 5), ("bar", 2)])
>>> {'foo': 5, 'bar': 2}

zip(*iterables) creates a zip object which yields tuples when iterated. In our case where we gave it two iterables (categories and items) it will yield tuple pairs, which is perfect for our use case:

list(zip(["foo", "bar"], [5, 2]))
>>> [('foo', 5), ('bar', 2)]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading