Dictionary in Python3

Hi  all . Today we are gonna see dictionary in python3.

In python2.7

d= {"a": "b", "b": "c", "c": "d", "d": "e", "e": "f"}

d.keys() —> [‘a’, ‘c’, ‘b’, ‘e’, ‘d’]

d.values() —> [‘b’, ‘d’, ‘c’, ‘f’, ‘e’]

Here d.keys() returns list of keys, d.values() returns list of values respectively.

In Python3 . These functions return dictkeys and dict values

d= {"a": "b", "b": "c", "c": "d", "d": "e", "e": "f"}
d.keys() ---> dict_keys(['d', 'c', 'b', 'e', 'a'])
d.values() ---> dict_values(['e', 'd', 'c', 'f', 'b'])

However if we want same functionality as 2.7 we can get like this

list(d.keys()) ---> ['d', 'c', 'b', 'e', 'a']
list(d.values()) ---> ['e', 'd', 'c', 'f', 'b']

There is no dict.iteritems(), d.has_key() function in python3

d.items() ---> dict_items([('d', 'e'), ('c', 'd'), ('b', 'c'), ('e', 'f'), ('a', 'b')])
list(d.items()) ---> [('d', 'e'), ('c', 'd'), ('b', 'c'), ('e', 'f'), ('a', 'b')]

Instead has_key() function we can check like this

'a' in d.keys() --> True
'z' in d.keys() --> False

If key doesn’t exists it will return false.

 

d.pop(‘a’) –> pop item from dict by key

d.popitem() –> pops most recently inserted item in dict

d.clear() –> clears entire dictionary

d.setdefault(‘z’, 10) –> sets default value for ‘z’ to 10

d.get(‘z’) –> 10 # gets value of key ‘z’, returns none if key doesn’t exist.

 

String Module In Python3

Hi all. After long time I’m writing a post . Finally started learning python internals and playing with c python source code little bit.

Its actually nice to read the source code of cpython . To get a copy of source code follow this Cpython .

Hope you have a running copy of cpython.  Inside the source code directory run ./python

i have version 3.5.0a0 like this

Python 3.5.0a0 (default:5754f069b123, Dec 13 2014, 00:41:29)
[GCC 4.8.2] on linux
Type “help”, “copyright”, “credits” or “license” for more information.
>>>

Here I’m not going to talk about python3 . Since i started coding and slowly moving to python3 from python2 (will explain module by module).

Lets start using string module. inside shell

import string

s = “this is my test string ”

print(string.capwords(s))

This Is My Test String

It just capitalize the first letter in every word in a given input string. The actual source code for capwords is

def capwords(s, sep=None):
    return (sep or ‘ ‘).join(x.capitalize() for x in s.split(sep))

you can check in file cpython/Lib/string.py

It just splits the words and capitalize and joins for result.

If you didn’t download source code . checking in ipython or bpython or python shell means . Don’t worry there is a another option to see the source code . Not only this module all the modules source code you can see .

Lets see that .

import inspect

inspect.getsource(string.capwords)

def capwords(s, sep=None):\n    “””capwords(s [,sep]) -> string\n\n    Split the argument into words using split, capitalize each\n    word using capitalize, and join the capitalized words using\n    join.  If the optional second argument sep is absent or None,\n    runs of whitespace characters are replaced by a single space\n    and leading and trailing whitespace are removed, otherwise\n    sep is used to split and join the words.\n\n    “””\n    return (sep or \’ \’).join(x.capitalize() for x in s.split(sep))\n’

See it returns source code in a string . How cool this inspect module ??. It has so many useful functions use it .

now coming back to our string module

string.ascii_letters

‘abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ’

string.ascii_lowercase

‘abcdefghijklmnopqrstuvwxyz’

string.ascii_uppercase

‘ABCDEFGHIJKLMNOPQRSTUVWXYZ’

I used to replace strings like this

k = “this is a test replace with b”

k.replace(‘a’,’b’)

I found this is less efficient than this one

test = str.maketrans(‘a’,’b’)

print(k.translate(test))

‘this is b test replbce with b’

Both functions does the same job but maketrans done in efficient way . It just creates mapping table and translates .

I test with time-it. Second one takes less time than first one .

%timeit k.replace(‘a’,’b’)
10000000 loops, best of 3: 167 ns per loop

%timeit k.translate(test)
10000000 loops, best of 3: 143 ns per loop

if you have noticed something  above,  i used str.maketrans(from,to)

In case of python 2.7+ to 3.

you can use like this

test = string.maketrans(‘a’,’b’)

print k.translate(test)

In python3.1maketrans () is not  a function of string module

Because in Python3 Strings are not bytes . Strings are Unicodes.

In python2  bytes was an alias for str.

You can check this in your shell

bytes is str   (In python2.7 shell)

True

bytes is str (In python3.5.0a0)

False

Hope you got something . Happy coding . Thanks for reading . Feel free to tell your suggestions .