Showing posts with label conversion. Show all posts
Showing posts with label conversion. Show all posts

Friday, May 1, 2015

Convert Strings,list of strings into a python dict or dictionary

"""
Strings ==> Dicts

"""

#problem1
#Input: s = "{'muffin' : 'lolz', 'foo' : 'kitty'}" --> a string
#output:  {'muffin' : 'lolz', 'foo' : 'kitty'} --> dictionary

>>> s
"{'muffin' : 'lolz', 'foo' : 'kitty'}"
>>> from ast import literal_eval
>>> literal_eval(s)
{'muffin': 'lolz', 'foo': 'kitty'}

>>> s
"{'muffin' : 'lolz', 'foo' : 'kitty'}"
>>> import json

>>> json_acceptable_string = s.replace("'", "\"")
>>> d = json.loads(json_acceptable_string)
>>> d
{'muffin': 'lolz', 'foo': 'kitty'}

"""
NOTE that if you have single quotes as a part of your keys or values this will fail due to improper character replacement

"""

#problem:2
#Input: mystring="a=0 b=1 c=3"
#output: {'a': 0, 'b': 1, 'c': 3}

"""
It's easy to convert list into a dict.

"""

In [1]: mystring = "a=0 b=1 c=3"

In [2]: mylist1=mystring.split() #using split for a string generates a list 

In [3]: mylist1
Out[3]: ['a=0', 'b=1', 'c=3']

In [4]: mylist2=[]

In [5]: for i in mylist1: #for every element in list1 i'm caling split at '='
   ...:     mylist2.append(i.split('='))
   ...:     

In [6]: mylist2
Out[6]: [['a', '0'], ['b', '1'], ['c', '3']]

In [7]: dict(mylist2)
Out[7]: {'a': '0', 'b': '1', 'c': '3'} #it worked but values in dictonary are strings not ints

In [8]: mylist2
Out[8]: [['a', '0'], ['b', '1'], ['c', '3']]

#convert the value item into an int  i.e '0'->0, '1'->1,'3'->3  ; mylist2 has 3 lists 
#So for every list in mylist2 i want to change the first element into a int
#mylist2[0][1] is '0'
#mylist2[1][1] is '1'

In [9]: for lists in mylist2: 
   ...:     lists[1]=int(lists[1])
   ...:     

In [10]: mylist2
Out[10]: [['a', 0], ['b', 1], ['c', 3]]


#we can use a single line answer for this

In [1]: mystring = "a=0 b=1 c=3"

In [2]: dict( (n,int(v)) for n,v in (i.split('=') for i in mystring.split() ) )
Out[2]: {'a': 0, 'b': 1, 'c': 3}


#using eval to solve 
#try to avoid using eval.
#eval() interprets a string as code.
>>> a='2*3'
>>> eval(a)
6
mystring = "a=0 b=1 c=3"


In [3]: mydict=eval('dict(%s)'%mystring.replace(' ',','))

In [4]: mydict
Out[4]: {'a': 0, 'b': 1, 'c': 3}

"""
This one took  me a while to understand.

try this 
"""
In [27]: dict(a=0,b=2,c=3)
Out[27]: {'a': 0, 'b': 2, 'c': 3}
#After trying this i came to understand

In [25]: 'dict(%s)' % mystring.replace(' ',',')
Out[25]: 'dict(a=0,b=1,c=3)'

# Invoking eval on the above line gives us desired dictionary





#problem 3
#Input:list_with_strings=["name","Ajay Kumar","age",25,"place","India"]

#Output:{'age': 25, 'name': 'Ajay Kumar', 'place': 'India'} 

In [1]: list_with_strings=["name","Ajay Kumar","age",25,"place","India"]

In [2]: dict(zip(*[iter(list_with_strings)]*2))
Out[2]: {'age': 25, 'name': 'Ajay Kumar', 'place': 'India'}

"""
func(*a) is the same as func(a[0], a[1], a[2], a[3] ... a[n]) if ahad n arguments
* is an argument unpacking
More @ http://stackoverflow.com/questions/287085/what-do-args-and-kwargs-mean/287582#287582
"""
In [37]: list_with_strings=["name","Ajay Kumar","age",25,"place","India"] 

In [38]: l = [iter(list_with_strings)]*2

In [39]: l
Out[39]: [, ]

In [40]: dict(zip(l[0], l[1]))
Out[40]: {'age': 25, 'name': 'Ajay Kumar', 'place': 'India'}


In [41]: def foo(a,b,c,d):
   ....:     print a,b,c,d
   ....:     

In [42]: l=[0,1] 

In [43]: d={"d":3,"c":2}

In [44]: foo(*l,**d) #for arguments we use * and keyword arguments we use **
0 1 2 3

#Easy way to understand this

n [3]: my_iterable=iter(list_with_strings) #iter keyword makes it iterable 

In [4]: dict(zip(my_iterable,my_iterable))
Out[4]: {'age': 25, 'name': 'Ajay Kumar', 'place': 'India'}






Learn python for fun.The popular blog with questions and answers to the python.Solutions to facebookhackercup,codejam,codechef.The fun way to learn python with me.Building some cool apps.

Thursday, April 30, 2015

Convert strings to tuple in python

#Strings to tuple


>>> myname='cam'
>>> tuple(myname)
('c', 'a', 'm')
>>> (myname,) #did you see the trailing comma after myname, ??
('cam',)

#Problem 1
mylist=["('good', 'buono')", "('afternoon', 'pomeriggo')"]

#my list contains two elements and  they are strings not tuples.

>>> from ast import literal_eval

>>> [literal_eval(i) for i in mylist]

[('good', 'buono'), ('afternoon', 'pomeriggo')]


#problem2

#Input : ['aaa','bbb','ccc']
#output:[('aaa',),('bbb',),('ccc',)]

lst = ['aaa','bbb','ccc']
tpl_lst = [(i,) for i in lst]
>>> tpl_lst
[('aaa',), ('bbb',), ('ccc',)]


#problem 3

# Input : '1/2' ==> it's  a string
#output: (1,2)
>>> my_frac='1/2'
>>> my_frac.split('/')
['1', '2']

>>> my_frac = tuple(map(int, my_frac.split('/')))
>>> my_frac
(1, 2)

#problem 4

#Input: s = "a b c d"
#output1: [(a,a),(b,b),(c,c),(d,d)]
#output2:[(a, b), (b, c), (c, d)]

#Solution for output1

>>> s = "a b c d"
>>> w = s.split()
>>> w
['a', 'b', 'c', 'd']
#python 3.x
>>> list(zip(w,w))
[('a', 'a'), ('b', 'b'), ('c', 'c'), ('d', 'd')]

#python 2.7

>>> zip(w,w)
[('a', 'a'), ('b', 'b'), ('c', 'c'), ('d', 'd')]

#Solution 2:

#python 3.x
>>> list(zip(w,w[1:]))
[('a', 'b'), ('b', 'c'), ('c', 'd')]

#python 2.7

>>> zip(w,w[1:])
[('a', 'b'), ('b', 'c'), ('c', 'd')] 
"Check one more example from SO" Learn python for fun.The popular blog with questions and answers to the python.Solutions to facebookhackercup,codejam,codechef.The fun way to learn python with me.Building some cool apps.

Convert string or strings into a list in python

I always wanted a python cheatsheet where by looking could get an idea.Since i'm a novice programmer,i need to look at these snippets so that it will get into longterm memory
>> myname="cam"
>>> list(myname)
['c', 'a', 'm']
>>> myname.split()
['cam']

>>> "cam".split('c') # split at c and eliminate c
['', 'am']
>>> "cam".split('cam')
['', '']

>>> "cacacacacacccaaaa".split('c')  #split or break at c and remove c 
['', 'a', 'a', 'a', 'a', 'a', '', '', 'aaaa']
#observe the fist character it's empty string
# ""+"cacacacacacccaaa" will give us same string "cacacacacacccaaa"


>>> "cacacacacacccaaaa".split('a')
['c', 'c', 'c', 'c', 'c', 'ccc', '', '', '', '']


"""
Problem: I've a text which have a | seperators.
I need to make a list of numbers 

text = '2,4,6,8|10,12,14,16|18,20,22,24' 

Output:

[[2,4,6,8],[10,12,14,16,18],[18,20,22,24]]

"""

>>> list(text)
['2', ',', '4', ',', '6', ',', '8', '|', '1', '0', ',', '1', '2', ',', '1', '4', ',', '1', '6', '|', '1', '8', ',', '2', '0', ',', '2', '2', ',', '2', '4']

>>> text.split()
['2,4,6,8|10,12,14,16|18,20,22,24']

# but it's just one single string and i still see the seperators '|'

 >>> text.split('|')
['2,4,6,8', '10,12,14,16', '18,20,22,24']

"""wow we got rid of '|'
well this is okay but  it is a list of 3 strings 
'2,4,6,8'==>together one string"""


>>> len(text.split('|'))
3



 #we can use a for loop iterate over the list and add each element to a new list

>>> mynewlist=[]
>>> for i in text.split('|'):
...     mynewlist.append(i.split(','))
... 
>>> mynewlist
[['2', '4', '6', '8'], ['10', '12', '14', '16'], ['18', '20', '22', '24']]


 
#There's more cleaner way to do it.
#So let's use list comprehension to acheive this.


>>> text = '2,4,6,8|10,12,14,16|18,20,22,24' 
>>> my_data = [x.split(',') for x in text.split('|')]
>>> my_data
[['2', '4', '6', '8'], ['10', '12', '14', '16'], ['18', '20', '22', '24']] #but they are still strings

>>> [[int(y) for y in x.split(',')] for x in text.split('|')]
[[2, 4, 6, 8], [10, 12, 14, 16], [18, 20, 22, 24]]


#or alternatively we can use map function
#http://pythonnotesbyajay.blogspot.in/2013/03/imap-and-map-in-python.html
#Simple usage of map (it takes 3 arguments 1.function,2.iterable,3.iterable )

>>> x=[1,2,3]
>>> y=[4,5,6]
>>> map(pow,x,y)

>>> output=list(map(pow,x,y))
>>> output
[1, 32, 729]


>>> text = '2,4,6,8|10,12,14,16|18,20,22,24'
>>> strs1=text.split('|')

>>> [map(int,x.split(',')) for x in strs1] 
[[2, 4, 6, 8], [10, 12, 14, 16], [18, 20, 22, 24]]


#How do you change this string into list 'QH QD JC KD JS' ?

>>> 'QH QD JC KD JS'.split()
['QH', 'QD', 'JC', 'KD', 'JS']



More about Split
Return a list of the words in the string, using sep as the delimiter string. If maxsplit is given, at most maxsplit splits are done (thus, the list will have at most maxsplit+1 elements). If maxsplit is not specified, then there is no limit on the number of splits (all possible splits are made).
If sep is given, consecutive delimiters are not grouped together and are deemed to delimit empty strings (for example, '1,,2'.split(',') returns ['1', '', '2']). The sep argument may consist of multiple characters (for example, '1<>2<>3'.split('<>') returns ['1', '2', '3']). Splitting an empty string with a specified separator returns [''].
If sep is not specified or is None, a different splitting algorithm is applied: runs of consecutive whitespace are regarded as a single separator, and the result will contain no empty strings at the start or end if the string has leading or trailing whitespace. Consequently, splitting an empty string or a string consisting of just whitespace with a None separator returns [].
For example, ' 1 2 3 '.split() returns ['1', '2', '3'], and ' 1 2 3 '.split(None, 1) returns ['1', '2 3 '].



Learn python for fun.The popular blog with questions and answers to the python.Solutions to facebookhackercup,codejam,codechef.The fun way to learn python with me.Building some cool apps.