Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Directory help
#1
From what I understand {} creates an empty directory, like these three:

energies = {}
hour_energies = {}
annual_energy = {}
However what function does the square brackets have in directories? The code I am adapting uses them like this (within a for loop):

annual_energy = ac.sum()
 energies[name] = annual_energy
 hour_energies[name] = ac 
Thanks in advance!
Reply
#2
A dictionary is a collection of key-value pairs.  Using brackets is how you specify which key/value you want.

>>> items = {
...  "spam": "eggs",
...  "second": "element",
...  "key": "value",
...  42: "universe"
... }
>>>
>>> items
{'spam': 'eggs', 42: 'universe', 'key': 'value', 'second': 'element'}
>>> for key in items:
...   print("{0} => {1}".format(key, items[key]))
...
spam => eggs
42 => universe
key => value
second => element
Reply
#3
Ok thanks.

How would I call two keys?
 energies[name, module[i]] or energies[name][module[i]] ? 
Reply
#4
What does "two keys" mean to you?

Does it mean you're using a multidimensional array, where the value of one of the keys is, itself, another dictionary? Then the second. The first only makes sense if the keys are tuples.

>>> items = {
...   "key": "val",
...   ("two", "part"): "spam",
...   "sub-dict": {
...     "1": "11"
...   }
... }
>>> items
{'sub-dict': {'1': '11'}, ('two', 'part'): 'spam', 'key': 'val'}
>>> items["key"]
'val'
>>> items["two", "part"]
'spam'
>>> items["sub-dict"]["1"]
'11'
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020