Python – sort() vs sorted(list)

Coding

You can compare list using sort() or sorted(list), but be careful with sort() – >>> c = [(‘d’,4), (‘c’,3), (‘a’,1), (‘b’, 2)] >>> a = [(‘a’,1), (‘b’, 2), (‘c’,3), (‘d’,4)] >>> a.sort() == c.sort() True >>> >>> a = [(‘a’,1), (‘b’, 2), (‘c’,3), (‘d’,4)] >>> b = [(‘b’,2), (‘c’, 3), (‘a’,1)] >>> >>> a.sort() == […]

Read more >

Python – str.maketrans()

Coding

Working on a Python code, I had a requirement for removing the single/double quotes and open/close brackets from the string of below format — >>> text = “””with summary as (select ‘ … ‘p.col1,p.col2,p.col3, ROW_NUMBER() ‘ … ‘OVER(PARTITION BY p.col1,p.col3 ORDER BY ‘ … ‘p.col2) AS rk from (select * from (select ‘ … ‘col2, […]

Read more >

Expanding array to multiple rows – Athena

AWS

A single row in Athena table is stored as — select id, course, date from demo.course_tab where id=’1234567892′ id course date 1234567892 [95c3c1bc5873, 2e345b2eb678, 027b02599f4a, 8695a580520b, 5d453355d415, cdcc7682070b] 2019-06-13 The datatype for course column is array(string). Now, how can you get the output in below format – id course date 1 1234567892 95c3c1bc5873 2019-06-13 2 […]

Read more >

namedtuple to JSON – Python

Coding

In pgdb – PostgreSQL DB API, the cursor which is used to manage the context of a fetch operation returns list of named tuples. These named tuples contain field names same as the column names of the database query. An example of a row from the list of named tuples – Row(log_time=datetime.datetime(2019, 3, 20, 5, […]

Read more >

Python List

Coding

This blog post is about appending data elements to list in Python. Suppose we have a simple list “x”, we will look at different ways to append elements to this list. x = [1, 2, 3] The “append” method appends only a single element >>> x [1, 2, 3] >>> x.append(4) >>> x [1, 2, […]

Read more >

Python – Flatten List of Lists

Coding

Itertools is one of the most powerful module in Python. Today I had requirement to flatten list of lists and itertools made it so easy. My list — >> val = [[‘a’,’b’],’c’,[‘d’,’e’,’f’]] Required Result [‘a’, ‘b’, ‘c’, ‘d’, ‘e’, ‘f’] How do you do it? Itertools to the resuce — >>> list(chain.from_iterable(val)) [‘a’, ‘b’, ‘c’, […]

Read more >