-2

Suppose I have the following list of dictionaries:

months = [
    {'id':'001','date':'January'},
    {'id':'002','date':'February'},
    {'id':'003','date':'March'},
    {'id':'004','date':'April'},
    {'id':'005','date':'May'},
    {'id':'006','date':'June'},
    {'id':'007','date':'July'},
    {'id':'008','date':'August'},
    {'id':'009','date':'September'},
    {'id':'010','date':'October'},
    {'id':'011','date':'November'},
    {'id':'012','date':'December'},
]

If the user enters the month as January, he should get the ID as 001.

I tried this, but it returns me a list of Months only.

res = [ mon['date'] for mon in months]

I need the id directly from the key itself. How can I achieve that ?

Vai
  • 333
  • 2
  • 15

5 Answers5

6

You can use the month as the key in a dictionary:

res = {mon['date']: mon['id'] for mon in months}
print(res['January'])
Anonymous
  • 11,347
  • 6
  • 32
  • 56
1

You convert what you have to a dict that maps from months to ids

new_dict = {item['date']: item['id'] for item in months}
blue_note
  • 25,410
  • 6
  • 56
  • 79
1

I hope this code will work for you.

month_name = input("Enter month name.")
dic = next(item for item in months if item["date"] == month_name)
id = dic["id"]
print(id)

I have tested this code on my local, and it works good.

ysk silver
  • 162
  • 8
0

it should be id instead of date

res = [ mon['id'] for mon in months]
hithyshi
  • 583
  • 1
  • 4
  • 10
0

Use if to filter within the list comprehension:

id = [m['id'] for m in months if m['date'] == 'January'][0]
Nick Lee
  • 5,169
  • 2
  • 25
  • 34