An elegant way to find unique pairs of strings from dictionary values ​​in a dictionary list

I have a list of dictionaries:

    some_list = [
                  {
                     item1:'a', 
                     item2:['1', '2']
                  }, 
                  {
                     item1:'b', 
                     item2:['1', '2']
                  }, 
                  {
                     item1:'a', 
                     item2:['1']
                  }
                ]

I would like to get:

['a 1', 'a 2', 'b 1', 'b 2'], where each value from paragraph 1 is associated with the value from paragraph 2 for each dictionary, and then only unique lines remain.

I can imagine an obvious way to do this, namely:

  • iteration through some_list;
  • for each dictionary, get each ['item_1'] and each ['item_2']
  • for each of ['item_2'] do each ['item_1'] + '' + member
  • Now make the list into a set, and I have my own unique values.

I am wondering if this is a more elegant way to do this using list comprehension.

+4
3

, -comprehnsion ( list, ):

In [1]: some_list = [
   ...:                   {
   ...:                      'item1':'a',
   ...:                      'item2':['1', '2']
   ...:                   },
   ...:                   {
   ...:                      'item1':'b',
   ...:                      'item2':['1', '2']
   ...:                   },
   ...:                   {
   ...:                      'item1':'a',
   ...:                      'item2':['1']
   ...:                   }
   ...:                 ]

In [2]: {f"{d['item1']} {v}" for d in some_list for v in d['item2']}
Out[2]: {'a 1', 'a 2', 'b 1', 'b 2'}
+4
def fun(item):
     return [item[item1]+' '+k for k in item[item2]]
res = []
[res.append(fun(i)) for i in some_list if(fun(i)) not in res]
print res

+1

another formatting option, will return to 2.7

sorted(map(' '.join,
           {(d['item1'], v)
            for d in some_list
                for v in d['item2']}))

still "single-line", but with decorative line breaks and indentation

The internal comp list is the same as the other ans, independently of each other without seeing it 1st

+1
source

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


All Articles