Python/dictionaries: Difference between revisions

From XPUB & Lens-Based wiki
(Created page with "= Dictionaries in Python = == How to read/write dictionaries? == <source lang="python"> d = dict() # or d = {} # Key : Value structure d = { 'software' : 10 } # Read a v...")
 
No edit summary
 
(3 intermediate revisions by the same user not shown)
Line 1: Line 1:
= Dictionaries in Python =
= How to read/write dictionaries? =


== How to read/write dictionaries? ==
<syntaxhighlight lang="python">
 
<source lang="python">
d = dict()
d = dict()


Line 26: Line 24:
     print(f'{word} is not in the dictionary')
     print(f'{word} is not in the dictionary')


</source>
</syntaxhighlight>


== Sort a dictionary ==
= Sort a dictionary =


<source lang="python">
<syntaxhighlight lang="python">


keys = []
keys = []
# key : value
# key : value
for key, value in d.items():
for key, value in d.items():
Line 43: Line 42:
     print(f'{key} is here so many times:', d[key])
     print(f'{key} is here so many times:', d[key])


</source>
</syntaxhighlight>
 
[[Category:Python]]

Latest revision as of 11:07, 28 June 2023

How to read/write dictionaries?

d = dict()

# or

d = {}

# Key : Value structure
d = { 'software' : 10 }

# Read a value from the dictionary
print(d['software'])
# 10

# Add a new key to the dictionary
d['language'] = 6

word = 'hello'
if word in d:
    print(f'{word} is in the dictionary')
else: 
    print(f'{word} is not in the dictionary')

Sort a dictionary

keys = []

# key : value
for key, value in d.items():
    keys.append(key)

keys.sort()
print(keys)

for key in keys:
    print(f'{key} is here so many times:', d[key])