Perl to Python: Data types

Hashes / Dictionaries

A hash in Python is a dictionary.

Action

Perl

Python

Define an empty structure

%hash = ();

dict = {}

Fill a dictionary

%hash = ('server', 'mpilgrim', 'database', 'master');

dict = {"server":"mpilgrim", "database":"master"}

Set an element

$hash{'a'} = 'b';

dict['a'] = 'b'

Delete an element

delete $hash{'a'}

del dict['a']

Clear the structure

%hash = ();

dict.clear()

Get the keys

keys(%hash)

dict.keys()

Get the values

values(%hash)

dict.values()

Get a pair as a tuple

-

dict.items()

Check for the presence of a key

defined($hash{$key})

dict.has_key('key')

Get zero if the value is undefined

not needed

dict.get( 123, 0 )

Iterate over a hash

for (keys %hash)

for key, value in dict.iteritems()

Tuples

There is nothing similar in Perl. Tuples are immutable arrays.

Filling a tuple

tuple = ("a", "b", "mpilgrim", "z", "example")

Set a tuple with one value

tuple = (3, )

Get an element

tuple[2]

Get tuple into variables

x, y, z = tuple

Swap the values

x,y = y,x

Array / Lists

The arrays you know from Perl are called lists in Python.

Action

Perl

Python

Create an empty list

@array=();

list = []

Fill a list

@array=('a', 'b', 'mpilgrim');

list = [ "a", "b", "mpilgrim" ]

Get an element

$array[5]

list[5]

Get a slice

$array[3,4,7]

list[3,4,7]

Append a value

push @array, 3

list.append(3)

Append values

push @array, ('a','b')

list += [“a“, “b“]

Insert a value

-

list.insert(2, 'hello')

Get and remove the last element

pop @array

list.pop()

Get and remove the first element

shift @array

list.pop(0)

Concatenate lists

(@array1, @array2)

list1 + list2

Find an element

-

list.index("example")

Count the number of occurences in a list

-

list.count('test')

Check if an element is contained in a list

-

list.in(“element“)

if element in list: ...

Remove an element

-

list.remove(“element“)

Remove an element at a position

-

del list[3]

del list[3:5]

del list

Extend a list by another list

push @array, @otherarray

list.extend(otherlist)

Sort a list

sort @array

list.sort()
<!> It returns 'None' - not the list

Reverse the list

reverse @array

list.reverse()

Repeat a list

-

[1,2,3] * 2 => [1,2,3,1,2,3]

Convert a list (of strings) into a string

join(';', @array)

“;“.join(list)

Splitting a string into a list

string.split(“;“)

Create a list of numbers

(0 .. 4)

range(4) => [0, 1, 2, 3]

range(2,4) => [2, 3]

range(1,9,3) => [1, 4, 7] (steps)

List mapping (map a list into another list)

-

[element*2 for element in list]

Example: strip all elements of a string: [argument.strip() for argument in mylist]

Multiple lists: [x+y for x in xlist for y in ylist]

Map (call a function with multiple variables and return all results)

map(&foobar, (1, 24, 95))

list = map(foobar, [1, 24, 95])

list = map(foobar, [1, 2, 3], [4, 5, 6]) <= each array delivers one argument for the function

Filter (call a function and return all arguments for which the result is true)

-

list = filter(foobar, [1, 3, 4])

Reduce (use the results of the function as the argument of the next call of the function)

-

result = reduce(foobar, [1, 2, 3]

=> result = foobar(foobar(1, 2), 3)

Enumerate a list

-

enumerate(['a','b','c']) => [[1,'a'], [2,'b'], [3,'c']]

Zip through multiple lists (use one member of each array)

-

for x, y in zip(list1, list2)

Aliasing:  a=[1,2,3] // b=a 

Copying:  a=[1,2,3] // b=a[:] 

Sets

A set is similar to a list. Just that each member is unique (like a key in a dictionary/hash) and the members are immutable. There is no such thing in Perl.

See http://www.python.org/doc/current/lib/types-set.html

<!> You will often use sets when you need a list of unique things. In Perl you usually abuse hashes for that and just use their keys. Imagine you need to get a list of distinct URLs from a log file.

Tricks with variables

Declare multiple variables

(x, y, z) = v

Create an enum

(MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY) = range(7)

Strings

<!> Strings are immutable. You can only create new strings with parts of the old string but not change parts of it. string.strip() is completely useless because it does not alter the string itself but returns a trimmed string just that you do not use the return code. Use string = string.strip() instead.

Parts of a string (substr in Perl)

string[3:5] / string[4] / string[ :3] / string[-1]

Raw strings

r“hello world\n“

Convert anything into a string

str(anything)

Right-pad

string.rjust(5)

Left-pad

string.ljust(5)

Center string

string.center(20)

Length of a string

len(string)

Go through the string char-by-char

for char in string:

Strip off newlines (chomp)

mystring.rstrip('\n')

The string modules (import string) provides more useful methods:

Find a substring

string.find(mystring, pattern, startpos, endpos)

Split a string into a list

string.split(mystring [, delimiter])

Join a list into a string

string.join(list [, delimiter])

The online help spits out the built-in string methods using help(str).

Numbers

<!> Numbers are integers by default. If you want to say 5/7 you should rather say 3/7.0 for an implicit cast.

Zero-fill a number

number.zfill(8)

WorkaroundOrg: PerlToPython/DataTypes (last edited 2005-08-29 17:54:57 by ChristophHaas)