Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Populate dictionary from list

I have a list of strings (from a .tt file) that looks like this:

list1 = ['have\tVERB', 'and\tCONJ', ..., 'tree\tNOUN', 'go\tVERB']

I want to turn it into a dictionary that looks like:

dict1 = { 'have':'VERB', 'and':'CONJ', 'tree':'NOUN', 'go':'VERB' }

I was thinking of substitution, but it doesn't work that well. Is there a way to tag the tab string '\t' as a divider?

like image 662
lenakmeth Avatar asked Nov 23 '16 14:11

lenakmeth


People also ask

Can you turn a list into a dictionary?

To convert a list to dictionary, we can use list comprehension and make a key:value pair of consecutive elements. Finally, typecase the list to dict type.

Can a list be a key in a dictionary Python?

Second, a dictionary key must be of a type that is immutable. For example, you can use an integer, float, string, or Boolean as a dictionary key. However, neither a list nor another dictionary can serve as a dictionary key, because lists and dictionaries are mutable.

Can you append a list to a dictionary?

Yes, you can append to a dictionary in Python. It is done using the update() method. The update() method links one dictionary with another, and the method involves inserting key-value pairs from one dictionary into another dictionary.


2 Answers

Try the following:

dict1 = dict(item.split('\t') for item in list1)

Output:

>>>dict1
{'and': 'CONJ', 'go': 'VERB', 'tree': 'NOUN', 'have': 'VERB'}
like image 167
ettanany Avatar answered Nov 14 '22 04:11

ettanany


Since str.split also splits on '\t' by default ('\t' is considered white space), you could get a functional approach by feeding dict with a map that looks quite elegant:

d = dict(map(str.split, list1))

With the dictionary d now being in the wanted form:

print(d)
{'and': 'CONJ', 'go': 'VERB', 'have': 'VERB', 'tree': 'NOUN'}

If you need a split only on '\t' (while ignoring ' ' and '\n') and still want to use the map approach, you can create a partial object with functools.partial that only uses '\t' as the separator:

from functools import partial 

# only splits on '\t' ignoring new-lines, white space e.t.c 
tabsplit = partial(str.split, sep='\t')
d = dict(map(tabsplit, list1)) 

this, of course, yields the same result for d using the sample list of strings.

like image 37
Dimitris Fasarakis Hilliard Avatar answered Nov 14 '22 05:11

Dimitris Fasarakis Hilliard