,

Python – Pythonic Collection

Dictionaries

1. Unpythonic


if b != None:
      a = b
 else:
      a = c

1. Pythonic

 a = b or c

1. Unpythonic

if var is None:
   print("var is not set")

1. Pythonic

if not var:
   print("var is not set")

1. Unpythonic

print("------------------------------")

1. Pythonic

print("-"*30)

Keys

1. Unpythonic

mydict.has_key(key)

1. Pythonic

key in mydict

2. Unpythonic

not key in mydict

2. Pythonic

key not in mydict

3. Unpythonic
Version 1.

if key in mydict:
   mydict[key]=0
mydict[key]= mydict[key] + 1

Version 2.

if key in mydict:
   mydict[key]=1
else:
   mydict[key]= mydict[key] + 1

3. Pythonic

mydict[key] = mydict.get(key, 0) + 1

reason: mydict.get(key, DEFAULT_VALUE)

3. Pythonic alternative

mydict[key] = 1 if key not in mydict else mydict[key] + 1

More Clearly …

mydict[key] = 1 (if (key not in mydict) else (mydict[key] + 1))

2. Unpythonic

f,data=None,None
try:
   f = open(filepath,"r")
   data=f.read()
finally:
   if f:
      f.close()

2. Pythonic

data=None
with open(filepath,"r") as f
   data=f.read()

the “with statement” will close all file descriptor when leaving the “with block”

2. Unpythonic

s = set()
for line in mylist:
    if line:
       s.add(line)

2. Pythonic

s = set( [line for line in mylist if line] )

2. Unpythonic

newlist =[]
for line in mylist:
    if line:
       newlist.append(line)

2. Pythonic

newlist = [line for line in mylist if line]


Comments

Leave a Reply

Your email address will not be published. Required fields are marked *