My list of lists looks like this:
my_list = [[sub_list_1],[sub_list_2],...,[sub_list_n]]
Desired output
my_dict[1] = [sub_list_1]
my_dict[2] = [sub_list_2]
my_dict[n] = [sub_list_n]
I want the keys for the dictionary to be generated on their own. How can this be achieved in a pythonic way?
I look at certain questions like
Converting list of lists in dictionary python
Python: List of lists to dictionary
Converting nested lists to dictionary
but they either provide a list of keys or focus on using some information from the lists as keys.
Alternatively, I tried making a list of keys this way:
my_keys = list(range(len(my_list)))
my_dict = dict(zip(my_keys,my_list)
and it works but, this does not:
my_dict = dict(zip(list(range(len(my_list))),my_list))
This gives me a syntax error.
So in summary:
Is there a way to generate a dictionary of lists without explicitly providing keys?, and
Why does the combined code throw a syntax error whereas the two step code works?
I would recommend to use a dict comprehension to achieve what you want like in here, moreover I tried your implementation and haven't faced any issues (more details are more than welcome):
my_list = [["sub_list_1"],["sub_list_2"],["sub_list_3"]]
my_dict = dict(zip(list(range(len(my_list))),my_list))
alternative_dict = {iter:item for iter,item in enumerate(my_list)}
print("yours : " + str(my_dict))
print("mine : " + str(alternative_dict))
output:
yours : {0: ['sub_list_1'], 1: ['sub_list_2'], 2: ['sub_list_3']}
mine : {0: ['sub_list_1'], 1: ['sub_list_2'], 2: ['sub_list_3']}
Your syntax error is caused by your variable name try. try is allready a name in python. see try/except
This should do it
my_dict = {my_list.index(i) + 1: i for i in my_list}
Notice that I have added +1 to start at the key 1 instead of 0 to match your expectations
I received no error message when running your code:
>>> my_list = [["hello1"], ["hello2"]]
>>> my_dict = dict(zip(list(range(len(my_list))), my_list))
>>> my_dict
{1: ['hello1'], 2: ['hello2']}
You can create a dict of lists from a list of lists using a dict comprehension:
my_dict = {i: sub_list for i, sub_list in enumerate(my_list)}
Related
I'm just starting out at Python and need some help with dictionaries. I'm looking to add keys to a dictionary based on input that is a list with string elements:
Ex.
x = {}
a = ['1', 'line', '56_09', '..xxx..']
Now say a while loop has come to this list a. I try to add to the dictionary with this code:
if a[1] == 'line':
x[a[2]] = [a[-1]]
I want the dictionary to read x = { '56_09': '..xxx..'} and want to confirm that by printing it. Do i need to adjust the elements on the list to strings or is it something with the if statement that I need to change?
The one problem with your code is in the if block:
if a[1] == 'line':
x[a[2]] = [a[-1]]
Instead, it should be like this:
if a[1] == 'line':
x[a[2]] = a[-1]
What you did was creating a list with one element: the last element of the list a.
you can make a dict object form two lists using ZIP and dict()
dict(zip(list1,list2)).
I believe for your question make two list form the input list based on the requirement and use above syntax.
I think you need something like this : -
def check(x,a):
if 'line' in a[1]:
x[a[2]] = a[-1]
return x
After
check({},['1', 'line', '56_09', '..xxx..'])
if a[1]=='line':
x={a[2]:a[-1]}
dictionary comprehension Create a dictionary with list comprehension in Python
{r:"test" for r in range(10)}
I wanted to create a list of dictionaries in python. The usual way of creating a list worked for me. That is mylist = [{1:1},{2:2}]
However, when I tried creating it using a comprehension over range() function, mylist = [a:a for a in range(10)] I get syntax error.
But to my surprise, if I construct a set in the same manner, it works as expected. myset = {a:a for a in range(10)}
May I know why this is so? I am using Python3
I think you want something like this:
mylist = [{a:a} for a in range(10)]
You forgot about { and }.
In the second example, your myset is a dict, not a set:
In [8]: type(myset)
Out[8]: dict
In this example, { and } denote dictionary comprehension, not set comprehension.
You're missing a dictionary creation in your list comprehension:
mylist = [{a:a} for a in range(10)]
I have a list in the following format:
['CASE_1:a','CASE_1:b','CASE_1:c','CASE_1:d',
'CASE_2:e','CASE_2:f','CASE_2:g','CASE_2:h']
I want to create a new list which looks like like this:
['CASE_1:a,b,c,d','CASE_2:e,f,g,h']
Any idea how to get this done elegantly??
You can use a defaultdict by treating case as the key, and appending to the list each letter, where case and the letter are obtained by splitting the elements of your list on ':' - such as:
from collections import defaultdict
case_letters = defaultdict(list)
start = ['CASE_1:a','CASE_1:b','CASE_1:c','CASE_1:d', 'CASE_2:e','CASE_2:f','CASE_2:g','CASE_2:h']
for el in start:
case, letter = el.split(':')
case_letters[case].append(letter)
result = sorted('{case}:{letters}'.format(case=key, letters=','.join(values)) for key, values in case_letters.iteritems())
print result
As this is homework (edit: or was!!?) - I recommend looking at collections.defaultdict, str.split (and other builtin string methods), at the builtin type list and it's methods (such as append, extend, sort etc...), str.format, the builtin sorted method and generally a dict in general. Use the working example here along with the final manual for reference - all these things will come in handy later on - so it's in your best interest to understand them as best you can.
One other thing to consider is that having something like:
{1: ['a', 'b', 'c', 'd'], 2: ['e', 'f', 'g', 'h']}
is a lot more of a useful format and could be used to recreate your desired list afterwards anyway...
I've deleted my full solution since I realized this is homework, but here's the basic idea:
A dictionary is a better data structure. I would look at a collections.defaultdict. e.g.
yourdict = defaultdict(list)
You can iterate through your list (splitting each element on ':'). Something like:
#only split string once -- resulting in a list of length 2.
case, value = element.split(':',1)
Then you can add these to the dict using the list .append method:
yourdict[case].append(value)
Now, you'll have a dict which maps keys (Case_1, Case_2) to lists (['a','b','c','d'], [...]).
If you really need a list, you can sort the items of the dictionary and join appropriately.
sigh. It looks like the homework tag has been removed (here's my original solution):
from collections import defaultdict
d = defaultdict(list)
for elem in yourlist:
case, value = elem.split(':', 1)
d[case].append(value)
Now you have a dictionary as I described above. If you really want to get your list back:
new_lst = [ case+':'+','.join(values) for case,values in sorted(d.items()) ]
data = ['CASE_1:a','CASE_1:b','CASE_1:c','CASE_1:d', 'CASE_2:e','CASE_2:f','CASE_2:g','CASE_2:h']
output = {}
for item in data:
key, value = item.split(':')
if key not in output:
output[key] = []
output[key].append(value)
result = []
for key, values in output.items():
result.append('%s:%s' % (key, ",".join(values)))
print result
outputs
['CASE_2:e,f,g,h', 'CASE_1:a,b,c,d']
mydict = {}
for item in list:
key,value = item.split(":")
if key in mydict:
mydict[key].append(value)
else:
mydict[key] = [value]
[key + ":" + ",".join(value) for key, value in mydict.iteritems()]
Not much elegance, to be honest. You know, I'd store your list as a dict, cause it behaves as a dict in fact.
output is ['CASE_2:e,f,g,h', 'CASE_1:a,b,c,d']
My list:
list = ['name1', 'option1.1 value1.1', 'option1.2 value1.2', 'name2', 'option2.1 value2.1', 'option2.2 value2.2', 'option2.3 value2.3']
And i want create dictionary like this:
dict = {'name1':{'option1.1':'value1.1', 'option1.2':'value1.2'}, 'name2':{'option2.1': 'value2.1', 'option2.2':'value2.2', 'option2.3':'value2.3'}
I don't know how big is my list (numbers of names, options and values). Any idea?
with list and dict comprehension:
id=[b[0] for b in enumerate(lst) if 'name' in b[1]]+[None]
d={lst[id[i]]:dict(map(str.split,lst[id[i]+1:id[i+1]])) for i in range(len(id)-1)}
your original list was here named lst
This is perhaps not as readable as the answer by #sr22222, but perhaps it's faster, and a matter of taste.
Assuming name will always be a single token (also, don't use list and dict as variable names, as they are builtins):
result = {}
for val in my_list:
split_val = val.split()
if len(split_val) == 1:
last_name = split_val[0]
result[last_name] = {}
else:
result[last_name][split_val[0]] = split_val[1]
Note that this will choke if the list is badly formatted and the first value is not a name.
I am trying to remove a dictionary from a list if it already exists but it doesn't seem to be working. Can anyone see what I am doing wrong or advise me what I should be doing
new_dict = {'value': 'some value', 'key': 'someKey'}
if new_dict in my_list:
my_list.remove(new_dict)
new_list is a list of dictionaries where new_dict is definitely in
If new_dict is "definitely" in my_list, then my_list.remove(new_dict) should do the trick (i.e., no need for the if new_dict in my_list, that just slows it down).
my_list = [1,{'value':'some value', 'key' :'somekey'}, 2, {'z':'z', 'x': 'x'}]
new_dict = {'value':'some value', 'key' :'somekey'}
#new_dict = {'z':'z', 'x': 'x'}
differ = 0
matched = 0
for element in my_list:
if type(element) is types.DictType and matched != 0:
differ = 0
# check if dictionary keys match
if element.viewkeys() == new_dict.viewkeys():
# check if dictionary values match
for key in element.keys():
if element[key] != new_dict[key]:
differ = 1
matched = 1
if differ != 1:
my_list.remove(new_dict)
print my_list
It worked for both of the dictionaries for me.
In most cases it is clever to build a new list:
new_list = [ dd for dd in my_list if not dd is new_dict ]
This is typical for a functional programming style, as it avoids side effects. Imagine if you use your solution in a function or method. In most cases you need a modified list only for internal purposes, then modifying an input parameter is dangerous.
Your problem may come from the fact that removing from a list while iterating over the same list is not safe. What you want to do is something like:
copied_list = my_list[:]
if new_dict in copied_list:
my_list.remove(new_dict)
This way, you iterate over a copy of the list and remove from the original.
This may not be the cause of your problem though. It would be interesting to see:
how you build my_list
what you do with my_list after the loop, i.e. how do you realise your dictionary was not removed