Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create a dictionary with list items as keys and indices as values?

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]
like image 567
Anshul Gupta Avatar asked Dec 13 '16 03:12

Anshul Gupta


People also ask

How do you create a dictionary using keys and values?

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.

Can you have a list as a value in a dictionary?

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 .

Can you have a list as a key in a dictionary?

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.

How do I convert a list to a dictionary key?

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.


1 Answers

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]}
like image 197
Psidom Avatar answered Nov 14 '22 21:11

Psidom