5

Probably a duplicate, but I can't find the answer by searching with these terms, at least.

Is there a quicker way to do this in Python?

level1 = {}
level2 = {}
level3 = {}

I've tried

level1 = level2 = level3 = {}

But that seems to create copies of the object, which isn't what I want. And

level1, level2, level3 = {}

throws an error.

5
  • 1
    that seems to create copies of the object - The code level1 = level2 = level3 = {} does not create any copies of the dict. Commented Dec 10, 2010 at 18:02
  • 2
    Just a terminology nitpick, but level1 = level2 = level3 = {} is in fact not creating copies. If it created a copy the behavior would be exactly what you want. Instead it is assigning all 3 to the same object, not copies of the object. Commented Dec 10, 2010 at 18:04
  • 6
    @Davy8 I don't think it's nitpicking when someone said the opposite of what they meant to say. Commented Dec 10, 2010 at 18:24
  • 1
    Also, Python doesn't "define" variables. It just assigns a name to an object. What tutorial are you using to learn Python? Commented Dec 10, 2010 at 19:08
  • You have gotten tons of solutions, but why are you trying to do this? Having to do what you're trying to do is so rare in Python code that I'm thinking you might be having an XY problem. Commented Jun 11, 2013 at 20:58

8 Answers 8

18
level1 = level2 = level3 = {}

Doesn’t create copies. It lets reference level{1-3} to the same object. You can use a list comprehension instead:

level1, level2, level3 = [{} for dummy in range(3)]

or more readable:

level1, level2, level3 = {}, {}, {}
Sign up to request clarification or add additional context in comments.

2 Comments

In Python vernacular, dummy is better indicated by a single underscore _
Not if u want to use _ for gettext.
15

Your variable naming is a possible sign that your design could be improved. It might be better to use a list instead of three separate variables:

levels = [{}, {}, {}]

2 Comments

Or use the list comprehension suggested by @nils: levels = [{} for _ in range(3)]
or for that matter levels = [] and add your dictionaries as you make them
13

You could do

level1, level2, level3 = {}, {}, {}

Comments

4
level1, level2, level3, = {}, {}, {}

Comments

1

I personally never change code to squeeze more stuff on one line. Have three different assignments is the way I would do it, one per line.

However, if there are documented performance improvements by making such a change, that's another thing. I just don't know of any performance improvements with these changes. Only obfuscation.

Comments

0

People have already answered the intent of your question, but...

Is there a quicker way to do this in Python?

What do you mean by quicker?

I think your real question should be "what is the pythonic way to do this?"

level1, level2, level3 = {}

From the Python documentation:

Tuples are constructed by the comma operator (not within square brackets), with or without enclosing parentheses, but an empty tuple must have the enclosing parentheses, such as a, b, c or (). A single item tuple must have a trailing comma, such as (d,).

a, b, c is implicitly (a, b, c). That's why you need to have a 3-tuple on the right side as suggested by other posters (nils, sdolan, gunner).

Shown explicitly they are suggesting this:

(level1, level2, level3) = ({}, {}, {},)

Comments

0

Python is interpreted which allows the definitions of things to be made at runtime.

def prefixed_range(prefix, start, stop=None, step=1):
    " Like xrange() but results are prefixed numeric strings. """
    prefix = str(prefix)
    if stop is None:
        start, stop = 0, start
    for i in xrange(start, stop, step):
        yield prefix + str(i)

def define_vars(names, value=None, namespace=None):
    namespace = globals() if not namespace else namespace
    factory = (lambda: value) if not callable(value) else value
    for name in names:
        namespace[name] = factory()

define_vars(prefixed_range('level', 1, 4), dict)

print 'level1: {}, level2: {}, level3: {}'.format(level1, level2, level3)
# level1: {}, level2: {}, level3: {}

Comments

-1

Try this: level1,level2,level3=[{}]*3

1 Comment

That would have the same problem.

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.