Home > other >  Dictionary value extract
Dictionary value extract

Time:07-15

I have a list with dict like following

[[{1:'a',2:'b'},{1:'g',2:'y'}],[{1:'r',2:'i'},{1:'t',2:'o'},{1:'q',2:'e'}],[{1:'p',2:'f'}]]

I want to extract output value as follows

a g - first value of first list
b y -second value of first list
r t q - first value of second list
i o e - second value of second list
p - first value of third list
f- second value of third list

I want output like Could anyone suggest how can I do this?

CodePudding user response:

If the dictionaries only ever have 1 and 2 as keys you could do this:

lst = [[{1:'a',2:'b'},{1:'g',2:'y'}],[{1:'r',2:'i'}]]
for i in lst:
    for k in (1, 2):
        print(*list(j.get(k, '') for j in i))

Output:

a g
b y
r
i

Edit: or if you don't know your keys in advance:

keys = {k for i in lst for j in i for k in j}
for i in lst:
    for k in keys:
        print(*list(j.get(k, '') for j in i))

CodePudding user response:

Here's a more robust solution if the dictionaries have keys other than 1 and 2:

def f(l):
  all_keys = []
  for e in l:
    for d in e:
      for i in d.keys():
        if i not in all_keys:
          all_keys  = [i]
  for e in l:
    for k in all_keys:
      l=[d.get(k) for d in e if d.get(k)]
      if l:
        print(*l)

f([[{1:'a',2:'b'},{1:'g',2:'y'}],[{1:'r',2:'i'},{1:'t',2:'o'},{1:'q',2:'e'}],[{1:'p',2:'f'}]])

Output:

a g
b y
r t q
i o e
p
f
  • Related