def show(post):
print(f”{post[‘text’]} – {post[‘likes’]}”)
posts = [
{“text”: “Hello”, “likes”: 3},
{“text”: “Hi”, “likes”: 5},
]
show(posts[0])
show(posts[1])
def show(post):
print(f”{post[‘text’]} – {post[‘likes’]}”)
posts = [
{“text”: “Hello”, “likes”: 3},
{“text”: “Hi”, “likes”: 5},
]
show(posts[0])
show(posts[1])
import copy
nums = [10, 20, 30, [40, 50]]
nums_bak = copy.deepcopy(nums)
nums[3][0] = 100
print(nums)
print(nums_bak)
from collections import defaultdict
results = [
(“pass”, “Taro”),
(“pass”, “Jiro”),
(“fail”, “Saburo”),
(“pass”, “Shiro”)]
stats = defaultdict(list)
for result, name in results:
stats[result].append(name)
print(dict(stats))
from collections import Counter
results = [“pass”, “pass”, “fail”, “pass”, “fail”, “pass”]
stats = Counter(results)
print(dict(stats))
from collections import defaultdict
results = [“pass”, “pass”, “fail”, “pass”, “fail”, “pass”]
stats = defaultdict(int)
for result in results:
stats[result] += 1
print(dict(stats))
results = [“pass”, “pass”, “fail”, “pass”, “fail”, “pass”]
stats = {}
for result in results:
if result not in stats:
stats[result] = 0
stats[result] += 1
print(stats)
from pprint import pprint
scores = [
{“name”: “Taro”, “math”: 70, “english”: 82},
{“name”: “Jiro”, “math”: 67, “english”: 61},
{“name”: “Saburo”, “math”: 81, “english”: 58},
]
pprint(scores)
file_name = “names.txt”
with open(file_name, mode=”r”) as f:
names = f.read().splitlines()
print(names)
file_name = “names.txt”
names = [“Jiro”, “Saburo”, “Shiro”]
with open(file_name, mode=”a”) as f:
for name in names:
f.write(f”{name}\n”)
import os
file_name = “names.txt
try:
with open(file_name, mode=”x”) as f:
f.write(“Saburo\n”)
except FileExistsError:
print(“File exists!”)