User Tools

Site Tools


python:python-code

Differences

This shows you the differences between two versions of the page.

Link to this comparison view

Next revision
Previous revision
python:python-code [10/07/2023 21:22] – created - external edit 127.0.0.1python:python-code [14/02/2025 10:48] (current) – [Print both keys and values] andrew
Line 1: Line 1:
 ====== Python code snippets ====== ====== Python code snippets ======
 +
 +===== FOR loop =====
 +
 +Looping through all the items in a dictionary.
 +
 +==== Print all the keys ====
 +
 +<code python>
 +exampledict = {
 +  "class": "Modified Hall",
 +  "engine": "Witherslack Hall",
 +  "built": "1948"
 +}
 +for x in thisdict:
 +  print(x)
 +</code>
 +<code>
 +class
 +engine
 +built
 +</code>
 +
 +
 +==== Print all the values - version 1 ====
 +
 +<code python>
 +exampledict = {
 +  "class": "Modified Hall",
 +  "engine": "Witherslack Hall",
 +  "built": "1948"
 +}
 +for x in exampledict:
 +  print(exampledict[x])
 +</code>
 +
 +<code>
 +Modified Hall
 +Witherslack Hall
 +1948
 +</code>
 +
 +
 +==== Print all the values - version 2 ====
 +
 +This uses the Python ".values()" function to get the values of each dictionary item.
 +<code python>
 +exampledict = {
 +  "class": "Modified Hall",
 +  "engine": "Witherslack Hall",
 +  "built": "1948"
 +}
 +for x in exampledict.values():
 +  print(x)
 +</code>
 +
 +<code>
 +Modified Hall
 +Witherslack Hall
 +1948
 +</code>
 +
 +
 +==== Print both keys and values ====
 +
 +Using the "items()" function to return both the value and the key for wach item.
 +
 +<code python>
 +exampledict = {
 +  "class": "Modified Hall",
 +  "engine": "Witherslack Hall",
 +  "built": "1948"
 +}
 +for x,y in exampledict.items():
 +  print(x, y)
 +</code>
 +
 +<code>
 +class Modified Hall
 +engine Witherslack Hall
 +built 1948
 +</code>
 +
 +
 +
 +
  
 ===== CLI input selection for an option ===== ===== CLI input selection for an option =====
python/python-code.1689024160.txt.gz · Last modified: by 127.0.0.1

Donate Powered by PHP Valid HTML5 Valid CSS Driven by DokuWiki