TransWikia.com

'for' loop does not loop correctly

Stack Overflow Asked on December 22, 2021

a=[['kyle','movie_1','c_13'],
   ['blair','food','a_29'],
   ['reese','movie_2','abc_76']]

b=['df.movie_1',
   'ghk.food',
   'df.movie_2']

x = {}
for i in b:
    y = i.split('.')
    for j in a:
        if y[1] in j : x[y[0]]=j

print(x)

This is my code to check if there is string inside a list a .
The output that I got is

{'df': ['reese', 'movie_2', 'abc_76'], 'ghk': ['blair', 'food', 'a_29']}

My desired output is

{'df': [['kyle','movie_1','c_13'],['reese', 'movie_2', 'abc_76']], 'ghk': ['blair', 'food', 'a_29']}

3 Answers

Hope This works: A single line code

Code:

op_dict={}
[op_dict.setdefault(x.split('.')[0], []).append(y) for x in b for y in a if x.split('.')[1] in y]

Output: Output lookslike

Answered by Praveen Sujanmulk on December 22, 2021

As mentioned in a previous answer, the problem is that your loops end up overwriting the value of x[y[0]]. Based on your desired output, what you need is to append to a list instead. There is already a nice solution using defaultdict. If instead you want to just use standard list, this is one way to do it:

a = [
      ['kyle','movie_1','c_13'],
      ['blair','food','a_29'],
      ['reese','movie_2','abc_76']]

b = [
      'df.movie_1',
      'ghk.food',
      'df.movie_2']

x = {}
for i in b:
    y = i.split('.')
    for j in a:
        if y[1] in j:
          if y[0] not in x:  # if this is the first time we append
            x[y[0]] = []     # make it an empty list
          x[y[0]].append(j)  # then always append

print(x)

Answered by sal on December 22, 2021

The cause is that the value would be cover when it exists x['df'].

You could use defaultdict to save them(A little different from you expect, though.But it is very easy):

from collections import defaultdict
a = [['kyle', 'movie_1', 'c_13'],
     ['blair', 'food', 'a_29'],
     ['reese', 'movie_2', 'abc_76']]

b = ['df.movie_1',
     'ghk.food',
     'df.movie_2']

x = defaultdict(list)
for i in b:
    y = i.split('.')
    for j in a:
        if y[1] in j:
            x[y[0]].append(j)

print(x)
# defaultdict(<class 'list'>, {'df': [['kyle', 'movie_1', 'c_13'], ['reese', 'movie_2', 'abc_76']], 'ghk': [['blair', 'food', 'a_29']]})

Answered by jizhihaoSAMA on December 22, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP