s =['Hello','World','Hello','World']
l = list()
for x,y in enumerate(s):
l.append((y,x))
The output I got is [('Hello', 0), ('World', 1), ('Hello', 2), ('World', 3)]
But I want
Hello-[0,2]
World-[1,3]
To create a Python dictionary, we pass a sequence of items (entries) inside curly braces {} and separate them using a comma ( , ). Each entry consists of a key and a value, also known as a key-value pair. Note: The values can belong to any data type and they can repeat, but the keys must remain unique.
Dictionaries use key:value pair to search if a key is present or not and if the key is present what is its value . We can use integer, string, tuples as dictionary keys but cannot use list as a key of it .
A dictionary or a list cannot be a key. Values, on the other hand, can literally be anything and they can be used more than once.
To convert a list to a dictionary using the same values, you can use the dict. fromkeys() method. To convert two lists into one dictionary, you can use the Python zip() function. The dictionary comprehension lets you create a new dictionary based on the values of a list.
You can use a dictionary:
d = {}
for i, v in enumerate(s):
if v in d:
d[v].append(i)
else:
d[v] = [i]
d
# {'Hello': [0, 2], 'World': [1, 3]}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With