How to convert each items of list into a dictionary? - python

Here I have a list like this.
ls = ['Small:u', 'Small:o']
What I want is to create a dictionary of each list items like this.
dict1 = {'Small':'u'}
dict2 = {'Small':'o'}
How can I do it ? Is it possible?

>>> x = [dict([pair.split(":", 1)]) for pair in ['Small:u', 'Small:o']]
>>> x
[{'Small': 'u'}, {'Small': 'o'}]

Yes, it is possible, but one thing I'm not sure whether is possible (or a good idea at all) is to programmatically assign variable names to new dictionaries, so instead the easier way is to create a dictionary of dictionaries:
dic_of_dics = {}
for index, item in enumerate(ls):
i, j = item.split(':')
dic_of_dics[f'dict{index}'] = {i : j}

This is another way:
ls = ['Small:u', 'Small:o']
dict_list = []
for i in ls:
k, v = i.split(':')
dict_list.append({k: v})
print(dict_list)
print(dict_list[1].values())

Perhaps with minimal line:
ls = ['Small:u', 'Small:o']
dict_list = map(lambda x:dict([x.split(':')]), ls)
# for python3: print(list(dict_list))
# for Python2: print(dict_list)
Explanation: I am using map function to convert the list of string to list of lists. Then I am passing it through dict(to convert them to dictionary).

Related

Nested Dictionaries in an empty dictionary

list1 = [[1,2,3],[4,5,6]]
list2 = ['a','b','c']
list3 = ['A','B']
main_list = [{k: dict(zip(list2, sub))} for k,sub in zip(list3, list1)]
print(main_list)
I am trying to work on this code, my goal is to write a dictionary within a nested dictionary. So, basically I'm trying to add the content in the main_list inside an empty dictionary. I'm hoping to get this ouput shown below:
{{'A':{'a':1, 'b':2, 'c':3}, {'B':{'a':4, 'b':5, 'c',6}}}
Please help:(
I think I found a solution:
main_dict = {k: v for i, k in enumerate(list3) for v in [{c: n for c, n in zip(list2, list1[i])}]}
I would not call it 'main_list', given it's a dict.

Parsing list items and returning a dictionary using comprehension

I have a two-items list which I need to process. Those items are retrieved from a database, so the are actually header: value pairs but they are unparsed. They are strings separated by tabs, so the list looks like this:
my_list = ['header1\theader2\theader3\theader4', 'val1\tval2\tval3\tval4']
I need to create dict from the key - value pairs. Currently I do it with list comprehension:
keys = [k.strip() for k in my_list[0].split('\t')]
vals = [v.strip() for v in my_list[1].split('\t')]
return dict(zip(keys, vals))
I think there might be a way doing that using dict comprehension instead, but I couldn't get how. Is it possible to do parse the list items and return a dictionary with a one-liner or a more pythonic way?
I find the solution below the most elegant one:
dict_comp = dict(zip(*map(lambda x: x.split('\t'), my_list)))
print(dict_comp) # -> {'header1': 'val1', 'header2': 'val2', 'header3': 'val3', 'header4': 'val4'}
Alternatively, the lambda can be substituted by a generator expression:
dict_comp = dict(zip(*(x.split('\t') for x in my_list)))
and if the strings do not contain any spaces, it can be shortened even further to:
dict_comp = dict(zip(*map(str.split, my_list))) # kudos #Chris_Rands
Try something like this
dict_comp = {k.strip():v.strip() for k,v in
zip(my_list[0].split('\t'), my_list[1].split('\t'))}

Not in list - List Comprehension

How can I add a condition in list comprehension like this? Ex:
Ex:
[dict if dict not in THIS.LIST for dict in tempList]
You had the order wrong, move the if to the end.
[dict for dict in tempList if dict not in THIS.LIST ]
Using your method python expects an else:
[dict if dict not in THIS.LIST else whatever for dict in tempList]
If you want to refer to the actual list you are creating use a for loop, if the items were hashable you could use a set to check if the element had already been seen with 0(1) lookups but if you have dicts then you won't be able to use a set with the dict directly:
res = []
for dct in temp_list:
if dct not in res:
res.append(dct)
Or a similar approach using a list comp, check from start of the list to the current index:
print([dct for ind, dct in enumerate(temp_list) if dct not in temp_list[:ind]])
If you just want to remove duplicate dicts we can use the dict.items:
temp_list = [ {1:2},{1:2}]
print([dict(items) for items in set(tuple(dct.items()) for dct in temp_list) ])
Or use an OrderedDict to keep order:
from collections import OrderedDict
temp_list = [ {1:2},{1:2}]
print(list(OrderedDict(((tuple(dct.items()),dct) for dct in temp_list)).values()))
Or again use a normal loop:
temp_list = [ {1:2},{1:2}]
seen = set()
out = []
for dct in temp_list:
tup = tuple(dct.items())
if tup not in seen:
out.append(dct)
seen.add(tup)
print(out)

How to iterate through dict values containing lists and remove items?

Python novice here. I have a dictionary of lists, like so:
d = {
1: ['foo', 'foo(1)', 'bar', 'bar(1)'],
2: ['foobaz', 'foobaz(1)', 'apple', 'apple(1)'],
3: ['oz', 'oz(1)', 'boo', 'boo(1)']
}
I am trying to figure out how to loop through the keys of the dictionary and the corresponding list values and remove all strings in each in list with a parantheses tail. So far this is what I have:
for key in keys:
for word in d[key]...: # what else needs to go here?
regex = re.compile('\w+\([0-9]\)')
re.sub(regex, '', word) # Should this be a ".pop()" from list instead?
I would like to do this with a list comprehension, but as I said, I can't find much information on looping through dict keys and corresponding dict value of lists. What's the most efficient way of setting this up?
You can re-build the dictionary, letting only elements without parenthesis through:
d = {k:[elem for elem in v if not elem.endswith(')')] for k,v in d.iteritems()}
temp_dict = d
for key, value is temp_dict:
for elem in value:
if temp_dict[key][elem].find(")")!=-1:
d[key].remove[elem]
you can't edit a list while iterating over it, so you create a copy of your list as temp_list and if you find parenthesis tail in it, you delete corresponding element from your original list.
Alternatively, you can do it without rebuilding the dictionary, which may be preferable if it's huge...
for k, v in d.iteritems():
d[k] = filter(lambda x: not x.endswith(')'), v)

Python dictionary: Remove all the keys that begins with s

I've got a dictionary like
dic = {'s_good': 23, 's_bad': 39, 'good_s': 34}
I want to remove all the keys that begins with 's_'
So in this case first two will be removed.
Is there any efficient way to do so?
This should do it:
for k in dic.keys():
if k.startswith('s_'):
dic.pop(k)
for k in dic.keys():
if k.startswith('s_'):
del dic[k]
* EDIT *
now in python 3 , years after the original answer, keys() returns a view into the dict so you can't change the dict size.
One of the most elegant solutions is a copy of the keys:
for k in list(dic.keys()):
if k.startswith('s_'):
del dic[k]
With python 3 to avoid the error:
RuntimeError: dictionary changed size during iteration
This should do it:
list_keys = list(dic.keys())
for k in list_keys:
if k.startswith('s_'):
dic.pop(k)
You can use a dictionary comprehension:
dic = {k: v for k, v in dic.items() if not k.startswith("s_")}
Note that this creates a new dictionary (which you then assign back to the dic variable) rather than mutating the existing dictionary.
How about something like this:
dic = dict( [(x,y) for x,y in dic.items() if not x.startswith('s_')] )

Categories