Python : Create a dictionary from a list

Creating a dictionary from a list containing elements of the type “variable=value”
Given a list _list = [ ‘days=7’, ‘months=12’, ‘pi=3.17’, ‘moon=1’ ]
Objective is to create a dictionary _dict = { ‘days’ : ‘7’, ‘months’ : ‘12’, ‘pi’ : ‘3.17’, ‘moon’ : ‘1’ }


Python3 : Creating a dictionary from a list using split

_list = [ 'days=7', 'months=12', 'pi=3.17', 'moon=1' ]
_dict = dict(item.split('=') for item in _list)

print("Given list : " + str(_list))
print("Created dictionary : " + str(_dict))

Output

Given list : ['days=7', 'months=12', 'pi=3.17', 'moon=1']
Created dictionary : {'days': '7', 'months': '12', 'pi': '3.17', 'moon': '1'}


A slight variation to the above would be when some elements in the list don’t have a value. For example consider the below…

Given a list _list = [ ’true’, ‘days=7’, ‘false’, ‘months=12’, ‘pi=3.17’, ‘fun’, ‘moon=1’ ]
Objective is to create a dictionary _dict = { ’true’ : ‘NONE’, ‘days’ : ‘7’, ‘false’ : ‘NONE’, ‘months’ : ‘12’, ‘pi’ : ‘3.17’, ‘moon’ : ‘1’ }

Python3 : Creating a dictionary from a list using regex search

import re

_list = [ 'true', 'days=7', 'false', 'months=12', 'pi=3.17', 'fun', 'moon=1' ]

_dict = {}
for item in _list:
  x = re.search(r'.*=.*', item)
  if x:
     key, value = item.split('=')
     _dict[key] = value
  else:
     _dict[item] = 'NONE' 

print("Given list : " + str(_list))
print("Created dictionary : " + str(_dict))

Output

Given list : ['true', 'days=7', 'false', 'months=12', 'pi=3.17', 'fun', 'moon=1']
Created dictionary : {'false': 'NONE', 'months': '12', 'days': '7', 'moon': '1', 'fun': 'NONE', 'pi': '3.17', 'true': 'NONE'}


Copyright (c) 2019-2024, Algotree.org.
All rights reserved.