Home > Blockchain >  Optimum solution using for loop
Optimum solution using for loop

Time:07-29

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?

CodePudding user response:

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

CodePudding user response:

Can be done using dictionary comprehension:

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

{c: i for c, i in zip(categories, items)}

Output:

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

CodePudding user response:

You can use zip() function and then convert it to dictionary.

items=["apple","carrot","bike","dog"]
keys = ["fruit", "vegetable","vehicle","animal"]
ordered_items = dict(zip(keys, items))

print(ordered_items)
  • Related