How to make (list, dictionary) from:
n = ('banana', 5, 'apple', 400, 'orange', 250, 'peach', 300)
to :
(fruit -> price)
Example:
for..print all
banana -> 5
apple -> 400
orange -> 250
peach -> 300
How to make (list, dictionary) from:
n = ('banana', 5, 'apple', 400, 'orange', 250, 'peach', 300)
to :
(fruit -> price)
Example:
for..print all
banana -> 5
apple -> 400
orange -> 250
peach -> 300
You can use dict
and zip
:
n = ('banana', 5, 'apple', 400, 'orange', 250, 'peach', 300)
print(dict(zip(n[::2],n[1::2])))
{'orange': 250, 'peach': 300, 'banana': 5, 'apple': 400}
zip(n[::2],n[1::2])
creates [('banana', 5), ('apple', 400), ('orange', 250), ('peach', 300)]
then calling dict on the result creates key/value pairings from each tuple.
More efficiently using iter to avoid slicing and creating new lists:
n = ('banana', 5, 'apple', 400, 'orange', 250, 'peach', 300)
it = iter(n)
print(dict(zip(it,it)))
To print the items:
for fruit, cost in dict(zip(it,it)).items():
print("{} -> {}".format(fruit, cost))
apple -> 400
orange -> 250
banana -> 5
peach -> 300
If you just want pairs just use zip:
for fruit, cost in zip(it,it):
print("{} -> {}".format(fruit, cost))
banana -> 5
apple -> 400
orange -> 250
peach -> 300
dicts don't have order so that is why the output is in a different order between both.