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)
{
"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)]