0

Hi I would like to convert a list of dictionaries into a single dictionary of some of the items in the list: I have:

>>> print(dct_lst)
[{'id': 456, 'name': 'bar'}, {'id': 789, 'name': 'baz'}, {'id': 123, 'name': 'foo'}]

I want:

dct={'bar':None
     'baz':None
     'foof':None}

and I've tried (among other combinations):

>>> for i in dct_lst['name']:
...     btns[i]=None
... 
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: list indices must be integers, not str

How do I get what I need?

stdcerr
  • 13,725
  • 25
  • 71
  • 128
  • Does this answer your question? [Iterating over list of dictionaries](https://stackoverflow.com/questions/9152431/iterating-over-list-of-dictionaries) – sahasrara62 Mar 29 '21 at 23:54
  • 2
    you need to iterate over a a list of dictionary, that iterator object is dictionary, from that object you take the name value and add it to new dict `dict ={i['name']:None for i in dct_lst}` – sahasrara62 Mar 29 '21 at 23:56

1 Answers1

3

Consider utilizing a dict comprehension:

>>> dct_lst = [{'id': 456, 'name': 'bar'}, {'id': 789, 'name': 'baz'}, {'id': 123, 'name': 'foo'}]
>>> dct = {d['name']: None for d in dct_lst if 'name' in d}
>>> dct
{'baz': None, 'foo': None, 'bar': None}
Sash Sinha
  • 18,743
  • 3
  • 23
  • 40
  • @stdcerr I rarely do this, but may I ask why you haven't accepted my answer? I'm just curious what is wrong with it since you have so many points (aren't a new user). My answer is before the comment by 3 mins, has better formatting, variable names, and adds a defensive check as well. – Sash Sinha Apr 20 '21 at 16:49