Difference between revisions of "Control Flow, if statements etc.."

From rbachwiki
Jump to navigation Jump to search
Line 26: Line 26:
  for item in d:
  for item in d:
     print(item)
     print(item)
Create a dictionary view object
d.items()
output
dict_items([('k1', 1), ('k2', 2), ('k3', 3)])
Dictionary unpacking
for k,v in d.items():
    print(k)
    print(v)
output
k1
1
k2
2
k3
3
If you want to obtain a true list of keys, values, or key/value tuples, you can cast the view as a list:
list(d.keys())
output
['k1', 'k2', 'k3']
Remember that dictionaries are unordered, and that keys and values come back in arbitrary order. You can obtain a sorted list using sorted():
sorted(d.values())

Revision as of 20:30, 6 January 2019

Python If Statemts

name = "b"
if name == 'robert':
   print(name)
elif name == 'john':
   print(name)
else:
   print('wrong name')

Python Loops

list2 = [(2,4),(6,8),(10,12)]
for tup in list2:
   print(tup)

output

(2, 4)
(6, 8)
(10, 12)

Now with unpacking

for (t1,t2) in list2:
   print(t1)

Output

2
6
10

Another Example

d = {'k1':1,'k2':2,'k3':3}
for item in d:
   print(item)

Create a dictionary view object

d.items()

output

dict_items([('k1', 1), ('k2', 2), ('k3', 3)])

Dictionary unpacking

for k,v in d.items():
   print(k)
   print(v) 

output

k1
1
k2
2
k3
3

If you want to obtain a true list of keys, values, or key/value tuples, you can cast the view as a list:

list(d.keys())

output

['k1', 'k2', 'k3']

Remember that dictionaries are unordered, and that keys and values come back in arbitrary order. You can obtain a sorted list using sorted():

sorted(d.values())