Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating a list by iterating over a dictionary

I defined a dictionary like this (list is a list of integers):

my_dictionary = {'list_name' : list, 'another_list_name': another_list}

Now, I want to create a new list by iterating over this dictionary. In the end, I want it to look like this:

my_list = [list_name_list_item1, list_name_list_item2, 
                list_name_list_item3, another_list_name_another_list_item1]

And so on.

So my question is: How can I realize this?

I tried

for key in my_dictionary.keys():
    k = my_dictionary[key]
    for value in my_dictionary.values():
        v = my_dictionary[value]
        v = str(v)
        my_list.append(k + '_' + v)

But instead of the desired output I receive a Type Error (unhashable type: 'list') in line 4 of this example.

like image 855
Hisushi Avatar asked Mar 11 '23 16:03

Hisushi


1 Answers

You're trying to get a dictionary item by it's value whereas you already have your value.

Do it in one line using a list comprehension:

my_dictionary = {'list_name' : [1,4,5], 'another_list_name': [6,7,8]}

my_list = [k+"_"+str(v) for k,lv in my_dictionary.items() for v in lv]

print(my_list)

result:

['another_list_name_6', 'another_list_name_7', 'another_list_name_8', 'list_name_1', 'list_name_4', 'list_name_5']

Note that since the order in your dictionary is not guaranteed, the order of the list isn't either. You could fix the order by sorting the items according to keys:

my_list = [k+"_"+str(v) for k,lv in sorted(my_dictionary.items()) for v in lv]
like image 149
Jean-François Fabre Avatar answered Mar 13 '23 05:03

Jean-François Fabre