Home > Software design >  How to get a particular key value pair from a dict in Python
How to get a particular key value pair from a dict in Python

Time:05-18

I have a dict like below

d = {"a":0,"b":1,"c":2}

I need to get only this in my output dict

out = {"b":1}

tried converting the dict to list and accessing the index 1, but it gives me tuples. Is there any workaround for this

print(list(d.items())[1])
("b",1)

CodePudding user response:

You could do out = {elem:d[elem] for idx,elem in enumerate(d) if idx in [0,1]} to select the indexes in [0,1] but dict([list(d.items())[1]]), as metioned by @Anetropic, works fine as well.

CodePudding user response:

What is the source of your key value? If you want to get all the items in dictionary from a key container:

>>> keys = ['b', 'c']
>>> {key: d[key] for key in keys}
{'b': 1, 'c': 2}

If you just want to get it in order from d.items():

>>> from itertools import islice
>>> dict(islice(d.items(), 1, 3))
{'b': 1, 'c': 2}
  • Related