About python dictionaries

python

#1

Hello guys, I have been working with a python- project for a few days, and now I got this problem. I have just slightly python- experience outside Codecademy, so I don't know about the syntax in the newest Python versions. Anyways, is it in effect possible to DEFINE un-string variables inside dictionaries? My editor tells me about undefined variables, so do I have to define them before this? Also even the names of the dictionaries must be defined.... What to do?

Variation based on my current code:

dictionary == {
variable: 31,
another_one: 39,
third_one: 46,
}

print dictionary.keys()

Does the older python version (that I learned in Codecademy :unamused:) approve this? Do I have to give earlier values to the variables? Looking for answers to this.


#2

but you can simply make the keys strings, and not variables?

dictionary = {
  "string": 32,
}

also, declaring a dictionary requires a single equal sign, not two equal signs (that is for comparison)


#3

So I can declare them only as strings?
I don't know the exact python version but it gives me a syntax error about one equal sign AND if the name of the dictionary is not a string. :neutral_face: Strange a bit


#4

you can use variables, but you do need to define the variable beforehand. depending on what you use it for, strings might be easier.

I don't know what you did, but a double equal sign looks really wrong


#5

It looks wrong on my eye, too but my current python version (not the newest one) requires it.


#6

if you run the latest version python, how can you possible use print without parentheses? already since python3 print requires parentheses:

variable = "variable"
another_one ="another_one"
third_one = "third_one"
dictionary = {
variable: 31,
another_one: 39,
third_one: 46,
}

print(dictionary.keys())

#7

As I said, the version that I use is not the newest one. But thanks for help anyway, I think that I understood it. :slight_smile:
Thank you.


#8

i read that wrong then, so you get it now?


#9

Yep, so I can give values to the variables that have an earlier value. Thank you for help, anyway.


#10

yea, or use strings as keys directly:

dictionary = {
  "test": "test",
  5: 5,
}

integers are also valid keys. Using undefined variable is not possible.