scythargon
scythargon

Reputation: 3491

python syntax features

is it possible to do things like this:

def f():
  d={}
  d[1]='qwe'
  d[2]='rty'
  return d

a,b=f()[1:2]

not a,b=f()[1],f()[2] and not

t=f()
a,b=t[1],t[2]

I wont avoid extra lines and call function only once.

Upvotes: 0

Views: 87

Answers (3)

Lukas Graf
Lukas Graf

Reputation: 32580

It's unclear to me what it is exactly you want to do. You're indexing a dictionary by integers. Integers can be used as keys to a dictionary just fine, but it looks like a list would make more sense in your case. An important difference between dictionaries and lists is that dicts are not ordered. d[1] and d[2] will not necessarily be in first and second place in your example. So if you depend on the order, standard dictionaries won't work anyway (an OrderedDict would).

(The fact that your data structure is returned by a function f() doesn't make any difference here, so I'll ignore it for better readability)

If you got

lst = ['qwe', 'rty']

you can simply do

a, b = lst

to assign lst[0] to a, and lst[1] to b. Lists can also be sliced:

long_lst = range(1000)
a, b = long_lst[500:502]

If you actually do want do use a dictionary, you can access its components like this:

>>> d = {'a': 'AAA', 'b': 'BBB'}
>>> d.keys()
['a', 'b']
>>> d.values()
['AAA', 'BBB']
>>> d.items()
[('a', 'AAA'), ('b', 'BBB')]

But as stated above, even if they happen to be in the right order in this example, you can't rely on the order of a dictionary, it will change over time.

Upvotes: 2

Danica
Danica

Reputation: 28846

No; dictionary indexing doesn't support slicing, since it usually doesn't make any sense in dictionary keys.

You can roll it yourself, though, with something like

a, b = map(f().get, [1, 2])

or (thanks @DSM)

a, b = operator.itemgetter(1, 2)(f())

These are slightly different in that if the result of f() is missing 1 or 2 as keys, the first will default to assigning None and the second will raise KeyError. map(f().__getitem__, ...) should be equivalent to itemgetter, though probably slightly slower.

Upvotes: 1

Dmytro Sirenko
Dmytro Sirenko

Reputation: 5083

Yes, just use method dict.values():

x,y = f().values()[0:2]

Upvotes: 1

Related Questions