0

How to keep only 2nd items of dictionary and preserve the same format(list of dictionaries) in the output?

a = [{'a1':10,'b1':9},{'d1':10,'c1':9}]

Expected output

e = [{'b1':9},{'c1':9}]

Code i tried:

e = [dict(b.items())[1] for a in e]   #not getting o/p
prog
  • 1,073
  • 5
  • 17
  • 2
    Dictionaries aren't ordered, so the result could be different every time you run it.. – fsimonjetz Jun 11 '21 at 09:06
  • 1
    it is safe(r) to assume that dictionaries are not ordered and thus speaking of their *nth* element does not make much sense. Is there something else that sets those elements apart beside their (apparent) position in the dict? – Ma0 Jun 11 '21 at 09:06
  • 1
    ok, so even if i use ordereddict i could not able to access right? – prog Jun 11 '21 at 09:08
  • 2
    You cannot index a dict; not even orderedDIcts. There are still ways, like getting the `dct.items()`, indexing that and recasting to dict but Python is trying to tell you to reconsider.. – Ma0 Jun 11 '21 at 09:12

2 Answers2

2

Not very pretty, but should be working:

new_dict = dict()
for i in (a):
    new_dict[list(i.items())[1][0]] = list(i.items())[1][1]
    
print([new_dict])
>> [{'b1': 9, 'c1': 9}]

Please keep in mind though, that it should be working only for Python 3.7 and newer versions, as explained here.

Rafa
  • 564
  • 4
  • 12
  • 1
    This is not guaranteed to always give the same result. – fsimonjetz Jun 11 '21 at 09:15
  • Doesn't [this](https://stackoverflow.com/questions/39980323/are-dictionaries-ordered-in-python-3-6) say that it does? – Rafa Jun 11 '21 at 09:37
  • 1
    I was not aware of that, thank you Rafał for bringing this to my attention. That being said, it's only guaranteed for newer versions of Python so it's still something to keep in mind. – fsimonjetz Jun 11 '21 at 10:10
  • 1
    I will add that info to my answer so that it's clear for all :) thanks for a valuable input as well – Rafa Jun 11 '21 at 12:09
1

I'll use list comprehension

code:

a = [{'a1':10,'b1':9},{'d1':10,'c1':9}]
e = [{list(ele.items())[1][0]:list(ele.items())[1][1]} for ele in a]  
print(e)

result:

[{'b1': 9}, {'c1': 9}]
leaf_yakitori
  • 2,232
  • 1
  • 9
  • 21