|
Oktatás
* Programozás 2 + feladatsor + C feladatsor + Python feladatsor + GitHub oldal
* Szkriptnyelvek + feladatsor + quick link
* Adator. prog. + feladatsor + quick link
Teaching
• Prog. for Data Sci. ▸ exercises ▸ quick link
teaching assets
Félévek
* 2026/27/1 * archívum
Linkek
* kalendárium * tételsorok * jegyzetek * szakdolgozat / PhD * ösztöndíjak * certificates * C lang. * C# * D lang. * Java * Nim * Nim2 + exercises * XC=BASIC * old ✦C++, ✦Clojure, ✦Scala
[ edit | logout ] [ sandbox | passwd ]
|
See std/tables in the docs.
This is the equivalent of Python's dictionary (dict) data structure.
| (1) normal dict/table
|
#
#
#
#
#
# A) make an empty dict
d = {}
d2: dict[str, int] = {}
# B) init with values
movies = {
"Alien": 1979,
"The Terminator": 1984
}
# C) Print it. Insertion order is kept since Python 3.7
print(movies) # {'Alien': 1979, 'The Terminator': 1984}
# D) length
print(len(movies)) # 2, i.e. 2 key/value pairs
# E) get value
print(movies["Alien"]) # 1979
# print(movies["True Lies"]) # KeyError: 'True Lies'
# F) get value safely
print(movies.get("True Lies", -1)) # -1 (not found)
# G) set value / update value
movies["The Abyss"] = 1988 # set
movies["The Abyss"] = 1989 # update
del movies["The Abyss"] # remove it
# H) check if key is present
print("Alien" in movies) # True
# I) print key/value pairs
for k in movies:
print(f"{k}: {movies[k]}")
# Alien: 1979
# The Terminator: 1984
# J) get keys in a list, get values in a list
print(list(movies.keys())) # ['Alien', 'The Terminator']
print(list(movies.values())) # [1979, 1984]
# K) iterate over the items
for k, v in movies.items():
print(f"{k}: {v}")
# L) remove a key/value pair
del movies["Alien"]
print(movies) # {'The Terminator': 1984}
# del movies["abcd"] # KeyError exception
# M) print items in alphabetical order by key
greek = {
"o": "omega",
"b": "beta",
"a": "alpha",
"g": "gamma",
}
for k in sorted(greek.keys()):
print(f"{k} -> {greek[k]}")
# a -> alpha
# b -> beta
# g -> gamma
# o -> omega
# N) clear
movies.clear()
print(len(movies)) # 0
|
import std/algorithm # sorted
import std/sequtils # toSeq
import std/strformat # &"..."
import std/tables
# A) make an empty table
var d: Table[string, int]
var d2 = initTable[string, int]()
# B) init with values
var movies = {
"Alien": 1979,
"The Terminator": 1984
}.toTable
# C) Print it. The order is arbitrary!
echo movies # {"The Terminator": 1984, "Alien": 1979}
# D) length
echo movies.len # 2, i.e. 2 key/value pairs
# E) get value
echo movies["Alien"] # 1979
# echo movies["True Lies"] # KeyError exception
# F) get value safely
echo movies.getOrDefault("True Lies", -1) # -1 (not found)
# G) set value / update value
movies["The Abyss"] = 1988 # set
movies["The Abyss"] = 1989 # update
movies.del("The Abyss") # remove it
# H) check if key is present
echo "Alien" in movies # true
# I) print key/value pairs
for k in movies.keys():
echo &"{k}: {movies[k]}"
# The Terminator: 1984
# Alien: 1979
# J) get keys in a list, get values in a list
# .keys() and .values() are iterators
echo movies.keys().toSeq # @["The Terminator", "Alien"]
echo movies.values().toSeq # @[1984, 1979]
# K) iterate over the pairs
for k, v in movies.pairs():
echo &"{k}: {v}"
# L) remove a key/value pair
movies.del("Alien")
echo movies # {"The Terminator": 1984}
movies.del("abcd") # no error if not found
# M) print items in alphabetical order by key
let greek = {
"o": "omega",
"b": "beta",
"a": "alpha",
"g": "gamma",
}.toTable
for k in sorted(greek.keys().toSeq):
echo &"{k} -> {greek[k]}"
# a -> alpha
# b -> beta
# g -> gamma
# o -> omega
# N) clear
movies.clear()
echo movies.len # 0
|
Notes:
- As you can see, the Nim code is very similar to Python.
- A Python dict keeps the insertion order since version 3.7. However, in a Nim table, the order is arbitrary.
- In Nim if you want to keep the insertion order, you can use a specialized table called
OrderedTable.
- In Nim, a table has value semantics, similarly to the other Nim data structures.
- However, if you want Python-like reference semantics, Nim also has
TableRef (created with newTable). I'll cover that later.
- In Nim, it's very easy to create an immutable table. Simply make the table a
let variable. With var, the table will be mutable. A let table is completely immutable, as long as it’s a Table and not a TableRef.
Notice that a hash map in Nim is called Table. For me, it was a bit strange at first:
import std/sets
import std/tables
var
mySet: HashSet[string]
myTable: Table[string, int] # not HashMap
|
Blogjaim, hobbi projektjeim
* The Ubuntu Incident * Python Adventures * @GitHub * heroku * extra * haladó Python * YouTube listák
Debrecen | la France
[ edit ]
|