0

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']

1
  • You say "the return" but there is no return in the example. Commented May 9, 2021 at 17:38

3 Answers 3

3

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.

Sign up to request clarification or add additional context in comments.

3 Comments

are you saying by readability that any programmer should be able to read it and not just people that know the map function? I am not doing code-golf, was just wondering how I'd do it. not experienced enough with python.
@Scilla, I meant that one-liners aren't necessarily easier to read than two or more lines of code. They also aren't necessarily faster or easier to write. They're often fun to write, though, but not necessarily fun to read.
i know what you mean by not easy read. probably you're right too when it come to not being faster, unless you really know what you're doing. Anyhow, thanks for sharing.
1

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')

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.