Convert this list to a dictionary using Python

list = ['Name=Sachin\n', 'country=India\n', 'game=cricket\n']

I want this list to the dictionary with the keys as the Name, country, gameand values like Sachin, India, cricketas the corresponding values. I got this list using readlines()from a text file.

+4
source share
6 answers
>>> lst = ['Name=Sachin\n', 'country=India\n', 'game=cricket\n']
>>> result = dict(e.strip().split('=') for e in lst)
>>> print(result)
{'Name': 'Sachin', 'country': 'India', 'game': 'cricket'}
+11
source

Another way to use regex.

>>> lis = ['Name=Sachin\n','country=India\n','game=cricket\n']
>>> dict(re.findall(r'(\w+)=(\w+)',''.join(lis)))
{'Name': 'Sachin', 'game': 'cricket', 'country': 'India'}
+4
source

:

lst =['Name=Sachin\n','country=India\n','game=cricket\n']

dct = dict( (item.split('=')[0], item.split('=')[1].strip()) for item in lst )
print(dct)

# {'game': 'cricket', 'country': 'India', 'Name': 'Sachin'}

note: list ist !

strip() , - :

def splt(item):
    sp = item.strip().split('=')
    return sp[0], sp[1]

dct = dict( splt(item) for item in lst )
print(dct)
+2

:

my_list = ['Name=Sachin\n', 'country=India\n', 'game=cricket\n']
my_dict = {}

for entry in my_list:
    key, value = entry.strip().split('=')
    my_dict[key] = value

print my_dict

:

{'country': 'India', 'game': 'cricket', 'Name': 'Sachin'}

. list, Python.

, :

with open('input.txt', 'r') as f_input:
    my_dict = {}
    for entry in f_input:
        key, value = entry.strip().split('=')
        my_dict[key] = value

print my_dict
+1
answer = {}
with open('path/to/file') as infile:
    for line in infile:  # note: you don't need to call readlines()
        key, value = line.split('=')
        answer[key.strip()] = value.strip()
0

:

d = {
        k: v 
        for k, v in map(
                    lambda x: x.strip().split('='), 
                    yourlist
                    )
    }

And as Peter Wood suggested renaming a list variable so as not to obscure the built-in list.

0
source

Source: https://habr.com/ru/post/1607598/


All Articles