Showing posts with label list. Show all posts
Showing posts with label list. Show all posts

Wednesday, August 19, 2009

Python: How to convert a dictionary into a list of key-value

Using the list() function, we can convert a dictionary into a list of key-value tuple.
>>> x = {'a':1, 'b':2}
>>> x
{'a': 1, 'b': 2}
>>> y = list(x.items())
>>> y
[('a', 1), ('b', 2)
To convert back into dictionary, use the dict() function.
>>> z = dict(y)
>>> z
{'a': 1, 'b': 2}

Thursday, August 13, 2009

Python: Remove items from a list that occur in another list

Suppose that you have two list x and y. How to remove items from list x that occur in list y?

Method 1

>>> x = [1, 2, 3, 4, 5, 6, 7, 8]
>>> y = [4, 7, 9]
>>> list(set(x) - set(y))
[1, 2, 3, 5, 6, 8]

Method 2

>>> x = [1, 2, 3, 4, 5, 6, 7, 8]
>>> y = [4, 7, 9]
>>> [i for i in x if i not in y]
[1, 2, 3, 5, 6, 8]
I have presented two methods for removing items from list x that occur in list y. If you have better method, please leave a comment.

Sunday, May 31, 2009

How to choose a random item from a sequence in Python

To choose a random item from a list, use random.choice().

Here is an example.
>>> items = ['Proton', 'Honda', 'Toyota', 'Nissan']
>>> random.choice(items)
'Nissan'
>>> random.choice(items)
'Proton'
>>> random.choice(items)
'Toyota'
Another example of usage is to choose a random file from a directory.
>>> random.choice(os.listdir("C:"))
'ubuntu'
>>> random.choice(os.listdir("C:"))
'tex4ht'

Saturday, May 16, 2009

The intersection of two Python lists using Set

Set is unordered unique collection of objects.

We can use Set to find the intersection of two lists/tuples.

Suppose that we have two lists.
>>> x = [1, 2, 3, 4, 5]
>>> y = [2, 6, 7, 3]

To find the intersection of the two lists, first change both x and y to the Set type, then use the intersection method (&).
>>> set(x) & set(y)
{2, 3}

If we need the output in list type, apply the list command, to the output.
>>> list(set(x) & set(y))
[2, 3]

How to sort a Python tuple

Python tuple is immutable. Therefore, it cannot be changed.

To sort a Python tuple, we can create a new list using sorted() method.

If we still need it as a tuple, just apply tuple() to the new list.
>>> z = (1, 4, 3, 7, 2, 12, -3, 3)
>>> sorted_z = tuple(sorted(z))
>>> sorted_z
(-3, 1, 2, 3, 3, 4, 7, 12)

How to sort a Python list

Suppose that you have a Python list,

[1, 4, 3, 7, 2, 12, -3, 3]

that needed to be sorted.

The list can be sorted by directly applying the sort() method to the list, and indirectly by using the sorted().

Using sort()


The list will be sorted and the list will now become the new sorted list.
>>> y = [1, 4, 3, 7, 2, 12, -3, 3]
>>> y.sort()
>>> y
[-3, 1, 2, 3, 3, 4, 7, 12]

Using sorted()


The list will be sorted as a new list.

We can create a new sorted list, and the original remains.
>>> y = [1, 4, 3, 7, 2, 12, -3, 3]
>>> sorted(y)
[-3, 1, 2, 3, 3, 4, 7, 12]
>>> y
[1, 4, 3, 7, 2, 12, -3, 3]

Wednesday, May 13, 2009

Convert Strings to Integers/Floats in Python

Strings to integer

To convert a string to an integer:
>>> x = '1234'
>>> int(x)
1234

Strings to float

To convert a string to float:
>>> x = '1234'
>>> float(x)
1234.0

>>> y = '1234.678'
>>> float(y)
1234.6780000000001
but, convertion of '1234.678' to integer using int() will gives an error.
>>> int(y)
Traceback (most recent call last):
File "<pyshell#4>", line 1, in <module>
int(y)
ValueError: invalid literal for int() with base 10: '1234.678'
A workaround is by first converting to float, then to integer:
>>> y = '1234.678'
>>> int(float(y))
1234

List/tuple of strings to list of integers


  1. Using list comprehension
    >>> x = ['07', '11', '13', '14', '28']
    >>> [int(i) for i in x]
    [7, 11, 13, 14, 28]
  2. Using map
    >>> x = ['07', '11', '13', '14', '28']
    >>> list(map(int, x))
    [7, 11, 13, 14, 28]
    Mix of integers and floats
    >>> x = ['7.424124', '11', '13.423', '14.53453656', '28.2']
    >>> list(map(int, map(float, x)))
    [7, 11, 13, 14, 28]

List/tuple of strings to list of floats


  1. Using list comprehension
    >>> x = ['7.424124', '1', '13.423', '14.53453656', '28.2']
    >>> [float(i) for i in x]
    [7.4241239999999999, 1.0, 13.423,
    14.534536559999999, 28.199999999999999]
  2. Using map
    >>> x = ['7.424124', '1', '13.423', '14.53453656', '28.2']
    >>> list(map(float, x))
    [7.4241239999999999, 1.0, 13.423,
    14.534536559999999, 28.199999999999999]

Sunday, April 26, 2009

The intersection of two Python lists

Suppose that you have two lists, x and y. You can list out the items that are common to the two lists.
>>> x = [1,2,3,4,5]
>>> y = [2,6,7,3]
>>> [i for i in y if i in x]
[2, 3]
To see how many items found in the intersection.
>>> len([i for i in y if i in x])
2

Tuesday, February 24, 2009

Unzip a Python list

Suppose that you have a list with tuples as the member.
>>> test = [('x',1), ('y',2), ('z',3)]
We can unzip the list by using zip() in conjunction with the * operator.
>>> a, b = zip(*test)
>>> a
('x', 'y', 'z')
>>> b
(1, 2, 3)

Thursday, February 19, 2009

How to convert two Python lists into a dictionary

To convert two Python lists into a dictionary. First, pair the two list with the zip() function, as key-value pairs. The last step is to use the dict() constructor to build a dictionary directly from the key-value pairs.
>>> x = ['a', 'b', 'c']
>>> y = [1 ,2 ,3]
>>> dict(zip(x,y))
{'a': 1, 'c': 3, 'b': 2}

We can also zip the two lists together, as list of tuples, and use the dict() constructor for the iterator of that list.
>>> x = ['a', 'b', 'c']
>>> y = [1, 2, 3]
>>> dict(iter(list(zip(x, y))))
{'a': 1, 'c': 3, 'b': 2}

Sunday, November 23, 2008

python list in sql query as parameter

Suppose that we have a list [10, 20, 4, 6, 9], and we want to write a sql query to get the data for all elements of the list, like
select * from students where id in (10, 20, 4, 6, 9)
How to do that in Python? Actualy, it is very easy. Below are the list of techniques to do it:

Technique 1

id = [10, 20, 4, 6, 9]
sql = 'select * from studens where id in %s' % str(tuple(id))

Technique 2

id = [10, 20, 4, 6, 9]
sql = 'select * from studens where id in (%s)' % ','.join(map(str, id))

Technique 3

id = [10, 20, 4, 6, 9]
xx = ', '.join(id)
sql = 'select * from students where id in (%s)' % xx

Technique 4

id = [10, 20, 4, 6, 9]
sql = 'select * from studens where id in (' +
         ','.join(map(str, id)) + ')'

Technique 5

id = [10, 20, 4, 6, 9]
sql = 'select * from studens where id in (' +
         ','.join((str(n) for n in id)) + ')'

Technique 6

id = [10, 20, 4, 6, 9]
sql = 'select * from studens where ' +
         ' or '.join(('id = ' + str(n) for n in id))
I prefer the first technique. What about you? Do you have some other techniques to share? If you do, please leave a comment. Thank you.

Note: The above codes were tested using Sqlite3 and Python 2.5.

Wednesday, April 16, 2008

Python: Initialize list and tuple values

This tutorial will show on how to give a Python list an initial value.

To initialize a ten items list with values set to 0:
myList = [0]*10
If we need to have 5 items of a list with the value 0 and the rest 5 with the value 1:
myList = [0]*5 + [1]*5
To initialize a ten items tuple with values set to 0:
myTuple = (0,)*10
If we need to have 5 item in a tuple with the value 0 and the rest 5 with the value 1:
myTuple = (0,)*5 + (1,)*5
For list, don't forget the comma ','. It means one item.