1

I have a json like this:

{
    "team": [
        {
            "id": "1",
            "member_name": "name1",
            "some_other_key":"keyvalue1"                
        },
        {
            "id": "2",
            "member_name": "name2",
            "some_other_key": "keuvalue2"

        }
    ]
}

And I want to create a dict like this

 { "1": "name1","2":"name2"}

I have written code like this

user_mapping = {}
for user in users['team']:
    user_mapping[user['id']] = user['member_name'] 

but I wanted to know if there's a more pythonic way or efficient way to do this than the brute force approach I've used.

S3DEV
  • 8,768
  • 3
  • 31
  • 42
Sujay DSa
  • 1,172
  • 2
  • 22
  • 37

2 Answers2

4

Simply and straightforward:

user_mapping = {user['id']: user['member_name'] for user in users['team']}

Besides, your for loop approach is not a "brute-force". You would use the former approach when you need a more extended logic (with intermediate statements/conditions/expressions).

RomanPerekhrest
  • 88,541
  • 4
  • 65
  • 105
2

Yes, at least one: Comprehensions

user_mapping = { user['id']:user['member_name'] for user in users['team'] }

comprehensions are both faster and more pythonic than for loops

GPhilo
  • 18,519
  • 9
  • 63
  • 89