Converting this list into Dictionary using Python - python

list = ['Name=Sachin\n', 'country=India\n', 'game=cricket\n']
I want this list in a dictionary with keys as Name, country, game and values as Sachin, India, cricket as corresponding values. I got this list using readlines() from a text file.

>>> 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'}

Just another way using 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'}

in one line:
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 not a good variable name!
strip() is called twice which is not all that nice - this may be better:
def splt(item):
sp = item.strip().split('=')
return sp[0], sp[1]
dct = dict( splt(item) for item in lst )
print(dct)

The following should work:
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
This give you the following dictionary:
{'country': 'India', 'game': 'cricket', 'Name': 'Sachin'}
Note, you should not use a variable name of list as this is used as a Python function.
If you are reading from a file, you could do this is follows:
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

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()

Use dictionary comprehension:
d = {
k: v
for k, v in map(
lambda x: x.strip().split('='),
yourlist
)
}
And as Peter Wood suggested rename your list variable not to shadow the built-in list.

Related

is there a way to only have a value in a list if the key appears multiple times in a file?

I'm trying to make a dictionary from items in a file. What I have now works but I was wondering if there is a way to only have a list if the key is a duplicate that has different value.so, if I have this
micheal math 2
jim chem 3
jim math 3
pam cs 4
expected output:
{micheal:[math,2],jim: [[chem,3], [math,3]], pam: [cs,4]}
actual output:
{micheal:[[math,2]],jim: [[chem,3], [math,3]], pam: [[cs,4]]}
current code:
example_dict = {}
for line in dictionary:
line = (line.strip()).split(' ')
key = line[0]
if key not in example_dict
example_dict[key] = []
example_dict[key].append(line[1:])
return example_dict
With your current solution, go over your example_dict afterward and flatten values that only have one element, e.x.:
...
example_dict = {k: (v if len(v) > 1 else v[0]) for k, v in example_dict.items()}
return example_dict
It seems like it would make a lot of sense to use dictionaries instead of tuple lists as values.
example_dict = {}
for line in dictionary:
name, subject, grade = line.strip().split() # optional, but cleaner
if name not in example_dict:
example_dict[name] = {}
example_dict[name][subject] = grade
Result:
{'micheal': {'math': '2'},
'jim': {'chem': '3', 'math': '3'},
'pam': {'cs': '4'}}

Reformating a dictionary of list based on items in another list

I have a dictionary of lists like
source = {"name":["hans","james","mat"],"country":["spain"],"language":["english","french"]}
and another list like
data_not_avail = ["hans","spain","mat"]
How is it possible to reformat source dictionary into the following format
{
"exist":{"name":["james"], "language":["english","french"]},
"not_exist":{"name":["hans","mat"], "country":["spain"]}
}
I was trying to solve by finding the key of item which are present in list but it was not a success
data_result = {}
keys_list = []
for v in data_not_avail:
keys = [key for key, value in source.items() if v in value]
data_result.update({keys[0]:[v]})
keys_list.extend(keys)
This is a approach, you can use a list comprehension (or python built in filter) to filter every element within source lists with the content of data_not_avail.
data = {"exist": {}, "not_exist": {}}
for key, value in source.items():
data["exist"][key] = [v for v in value if v not in data_not_avail]
data["not_exist"][key] = [v for v in value if v in data_not_avail]
# if you dont need empty list in the result
if not data["exist"][key]:
del data["exist"][key]
if not data["not_exist"][key]:
del data["not_exist"][key]
Naive way of solving it is this, check it out.
values = list(source.values())
exist_values = []
not_values = []
for l in values:
temp_exist = []
temp_not = []
for item in l:
if item not in data_not_avail:
temp_exist.append(item)
else:
temp_not.append(item)
exist_values.append(temp_exist)
not_values.append(temp_not)
exist = {}
not_exist = {}
keys = ['name', 'language', 'country']
for i,key in enumerate(keys):
if len(exist_values[i]) != 0:
exist[key] = exist_values[i]
if len(not_values[i]) != 0:
not_exist[key] = not_values[i]
print(exist, not_exist)
#{'name': ['james'], 'country': ['english', 'french']}
#{'name': ['hans', 'mat'], 'language': ['spain']}

extract specific value from dictionary of list of dictionary

I have dataset like this:
{'project-1': [{'id':'1','name':'john'},{'id':'20','name':'steve'}],
'project-2': [{'id':'6','name':'jack'},{'id':'42','name':'anna'}]}
what I want to extract is the name of all people:
['john','steve','jack','anna']
How to get these list using python?
my_dict = {
'project-1': [{'id':'1','name':'john'},{'id':'20','name':'steve'}],
'project-2': [{'id':'6','name':'jack'},{'id':'42','name':'anna'}]
}
You can use a list comprehension it get the name field from each dictionary contained within the sublists (i.e. within the values of the original dictionary).
>>> [d.get('name') for sublists in my_dict.values() for d in sublists]
['john', 'steve', 'jack', 'anna']
Iterate over the dict, then over the values of the current dict:
for d_ in d.values():
for item in d_:
print item['name']
Or in comprehension
names = [item['name'] for d_ in d.values() for item in d_]
print names
['john', 'steve', 'jack', 'anna']
This should do it.
d = {'project-1': [{'id':'1','name':'john'},{'id':'20','name':'steve'}],
'project-2': [{'id':'6','name':'jack'},{'id':'42','name':'anna'}]}
result = list()
for key in d:
for x in d[key]:
result.append(x['name'])
Many solutions trying same old approach here using two loop:
Here is different approach:
One line solution without any loop:
You can use lambda function with map:
data={'project-1': [{'id':'1','name':'john'},{'id':'20','name':'steve'}],
'project-2': [{'id':'6','name':'jack'},{'id':'42','name':'anna'}]}
print(list(map(lambda x:list(map(lambda y:y['name'],x)),data.values())))
output:
[['john', 'steve'], ['jack', 'anna']]
name_id = {'project-1': [{'id':'1','name':'john'},{'id':'20','name':'steve'}], 'project-2': [{'id':'6','name':'jack'},{'id':'42','name':'anna'}]}
name_id['project-1'][0]['name'] = 'john'
name_id['project-1'][1]['name'] = 'steve'
name_id['project-2'][0]['name'] = 'jack'
name_id['project-2'][1]['name'] = 'anna'
The ['project-1'] gets the value corresponding to the project-1 key in the dictionary name_id. [0] is the list index for the first element in the dictionary value. ['name'] is also a key, but of the dictionary in the first element of the list. It gives you the final value that you want.

Python Iterating in a dictionary to get empty key's

Hello guys I'm trying to iterate from a dictionary to get the keys in case some of keys would be empty, but I have no idea how to achieve this.
Any idea ?
def val(**args):
args = args
print args
# print args
# print (args.keys())
val(name = '', country = 'Canada', phone = '')
Whit this example I got {'country': 'Canada', 'name': '', 'phone': ''} but when I'm really looking is to get only the keys of the empty keys in a list using append, the problem is that it gives me all the keys when and not just the empty keys.
In that case I would like to return something like this:
name, phone
I appreciate your help.
Iterate the dictionary and extract keys where the value is an empty string:
empty_keys = [k for k, v in args.items() if v == '']
or as a function:
>>> def val(**args):
... return [k for k, v in args.items() if v == '']
...
>>> val(name = '', country = 'Canada', phone = '')
['phone', 'name']
This is how you get a list of the empty keys:
empty = [k for k, v in args.items() if not v or v.isspace()]
Notice that the above includes the cases when the value is None or '' or only spaces.
The for statement can be used to iterate over the key/values of a dictionary, then you can do what you want with them.
def val(args) :
outputList = []
for k, v in args :
if v == '' :
outputList.append(k)
return outputList
This function will return a list made up of the keys whose value are the empty string.

How can I only parse/split this list with multiple colons in each element? Create dictionary

I have the following Python list:
list1 = ['EW:G:B<<LADHFSSFAFFF', 'CB:E:OWTOWTW', 'PP:E:A,A<F<AF', 'GR:A:OUO-1-XXX-EGD:forthyFive:1:HMJeCXX:7', 'SX:F:-111', 'DS:f:115.5', 'MW:AA:0', 'MA:A:0XT:i:0', 'EY:EE:KJERWEWERKJWE']
I would like to take the entries of this list and create a dictionary of key-values pairs that looks like
dictionary_list1 = {'EW':'G:B<<LADHFSSFAFFF', 'CB':'E:OWTOWTW', 'PP':'E:A,A<F<AF', 'GR':'A:OUO-1-XXX-EGD:forthyFive:1:HMJeCXX:7', 'SX':'F:-111', 'DS':'f:115.5', 'MW':'AA:0', 'MA':'A:0XT:i:0', 'EW':'EE:KJERWEWERKJWE'}
How does one parse/split the list above list1 to do this? My first instinct was to try try1 = list1.split(":"), but then I think it is impossible to retrieve the "key" for this list, as there are multiple colons :
What is the most pythonic way to do this?
You can specify a maximum number of times to split with the second argument to split.
list1 = ['EW:G:B<<LADHFSSFAFFF', 'CB:E:OWTOWTW', 'PP:E:A,A<F<AF', 'GR:A:OUO-1-XXX-EGD:forthyFive:1:HMJeCXX:7', 'SX:F:-111', 'DS:f:115.5', 'MW:AA:0', 'MA:A:0XT:i:0', 'EW:EE:KJERWEWERKJWE']
d = dict(item.split(':', 1) for item in list1)
Result:
>>> import pprint
>>> pprint.pprint(d)
{'CB': 'E:OWTOWTW',
'DS': 'f:115.5',
'EW': 'EE:KJERWEWERKJWE',
'GR': 'A:OUO-1-XXX-EGD:forthyFive:1:HMJeCXX:7',
'MA': 'A:0XT:i:0',
'MW': 'AA:0',
'PP': 'E:A,A<F<AF',
'SX': 'F:-111'}
If you'd like to keep track of values for non-unique keys, like 'EW:G:B<<LADHFSSFAFFF' and 'EW:EE:KJERWEWERKJWE', you could add keys to a collections.defaultdict:
import collections
d = collections.defaultdict(list)
for item in list1:
k,v = item.split(':', 1)
d[k].append(v)
Result:
>>> pprint.pprint(d)
{'CB': ['E:OWTOWTW'],
'DS': ['f:115.5'],
'EW': ['G:B<<LADHFSSFAFFF', 'EE:KJERWEWERKJWE'],
'GR': ['A:OUO-1-XXX-EGD:forthyFive:1:HMJeCXX:7'],
'MA': ['A:0XT:i:0'],
'MW': ['AA:0'],
'PP': ['E:A,A<F<AF'],
'SX': ['F:-111']}
You can also use str.partition
list1 = ['EW:G:B<<LADHFSSFAFFF', 'CB:E:OWTOWTW', 'PP:E:A,A<F<AF', 'GR:A:OUO-1-XXX-EGD:forthyFive:1:HMJeCXX:7', 'SX:F:-111', 'DS:f:115.5', 'MW:AA:0', 'MA:A:0XT:i:0', 'EW:EE:KJERWEWERKJWE']
d = dict([t for t in x.partition(':') if t!=':'] for x in list1)
# or more simply as TigerhawkT3 mentioned in the comment
d = dict(x.partition(':')[::2] for x in list1)
for k, v in d.items():
print('{}: {}'.format(k, v))
Output:
MW: AA:0
CB: E:OWTOWTW
GR: A:OUO-1-XXX-EGD:forthyFive:1:HMJeCXX:7
PP: E:A,A<F<AF
EW: EE:KJERWEWERKJWE
SX: F:-111
DS: f:115.5
MA: A:0XT:i:0

Categories

Resources