Scilla
Scilla

Reputation: 385

Assign multiple values based on key from dictionary python

Please consider this dictionary


dict = {
    "AccessKey": {
        "UserName": "string",
        "AccessKeyId": "string",
        "Status": "Active | Inactive",
        "SecretAccessKey": "string",
        "CreateDate": "datetime(2015, 1, 1)",
    }
}

What would be a way to assign values of the specified keys in one line, to vars?

x, y = dict['AccessKey'][AccessKeyId']['SecretAccessKey']

A solution would be:

x = dict['AccessKey']['AccessKeyId']

y = dict['AccessKey']['SecretAccessKey']

Upvotes: 0

Views: 50

Answers (3)

Ayush Garg
Ayush Garg

Reputation: 2527

A slightly more readable answer than @ForceBru's:

x, y = (dict['AccessKey'][item] for item in ('AccessKeyId', 'SecretAccessKey'))

which uses generator comprehension instead of map (and avoids the ugly .__getitem__). However, I agree with @ForceBru -

...but why? Code should aim for readability first. Unless you're doing code-golf, that is.

Upvotes: 1

Andrej Kesely
Andrej Kesely

Reputation: 195613

Another solution, using operator.itemgetter:

from operator import itemgetter

dct = {
    "AccessKey": {
        "UserName": "string",
        "AccessKeyId": "string",
        "Status": "Active | Inactive",
        "SecretAccessKey": "string",
        "CreateDate": "datetime(2015, 1, 1)",
    }
}

keys = "AccessKeyId", "SecretAccessKey"
print(itemgetter(*keys)(dct["AccessKey"]))

Prints:

('string', 'string')

Upvotes: 1

ForceBru
ForceBru

Reputation: 44926

Sure:

x, y = map(dict['AccessKey'].__getitem__, ('AccessKeyId', 'SecretAccessKey'))

...but why? Code should aim for readability first. Unless you're doing code-golf, that is.

Upvotes: 3

Related Questions