Creating a list by iterating through a dictionary

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

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

Now I want to create a new list, iterate 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]

Etc.

So my question is: how can I understand 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 get Type Error (unhashable type: 'list') on line 4 of this example.

+4
source share
6 answers

You are trying to get the meaning of a dictionary by its meaning, while you already have your own meaning.

Do this on one line using 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']

, , , . , :

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

:

my_list = []
for key in my_dictionary:
    for item in my_dictionary[key]:
        my_list.append(str(key) + '_' + str(item))

, .

+2

, , . items , :

["{}_{}".format(k,v) for k,v in d.items()]

, ; . ...

d={1:[1,2,3],2:[4,5,6]}
list(itertools.chain(*(
      ["{}_{}".format(k,i) for i in l]
      for (k,l) in d.items() )))

. , , , . , * , , .

Edit: , Python 3.4.3 , ; , - k l, .

: - ( ), . :

["{}_{}".format(k,v) for k,l in d.items() for v in l]

- .

0

, dict().values() - , , , , 4, ( ) . , , {1:2, 3:4}, KeyError, {1:2, 2:1} , , , .

, , ; .

def f()
    a = 1
    b = 2
    c = 3
    l = [a, b, c]

    return l

f() [1, 2, 3], a, b c .

, , .extend() :

my_list = my_dictionary['list_name'][:]
my_list.extend(my_dictionary['another_list_name'])

, , OrderedDict .

0

,

d = {"test1":[1,2,3,],"test2":[4,5,6],"test3":[7,8,9]}

new_list = [str(item[0])+'_'+str(v) for item in d.items() for v in item[1]]

:

new_list:
['test1_1',
 'test1_2',
 'test1_3',
 'test3_7',
 'test3_8',
 'test3_9',
 'test2_4',
 'test2_5',
 'test2_6']
0

In [1]: l0 = [1, 2, 3, 4]

In [2]: l1 = [10, 20, 30, 40]

In [3]: d = {'name0': l0, 'name1': l1}

, , , ... ?

, , str(...).

... , (, ) , .

In [4]: res = ['_'.join((str(k), str(i))) for k, l in d.items() for i in l]

In [5]: print(res)
['name0_1', 'name0_2', 'name0_3', 'name0_4', 'name1_10', 'name1_20', 'name1_30', 'name1_40']

In [6]: 

str(k)+'_'+str(i) , 'text' 'text'.join(...). , .join SINGLE-, , , join((..., ...)) .

0

Source: https://habr.com/ru/post/1660476/


All Articles