how to strip off from all the braces from a dict

This is the place for queries that don't fit in any of the other categories.

how to strip off from all the braces from a dict

Postby lovecodecakes » Sat Apr 13, 2013 9:26 pm

And return only tuple values as in the following case:
Q2: How to count total values in the same key????

Code: Select all
def age_swap():
   reversible_ages={}
   moms_age=int(raw_input('enter your moms current age:\t'))
   baby_age=int(raw_input('enter your current age:\t'))
   expectancy=int(raw_input('for how long your mom\'s age do you want to theoretically want to compare age swap?:\t'))
   mom_wen_uborn=moms_age-baby_age
   reversible_ages.setdefault('You:Mom', []).append([(baby,imom) for baby,imom in enumerate(xrange(mom_wen_uborn,expectancy)) if str(baby)[:]==str(imom)[::-1]])
   ra=[(''.join(str(v).strip())) for k,v in reversible_ages.iteritems()]
   count=len(ra) #count=len(list(reversible_ages))
   return 'No. of times that happens for is %s' %(count), ''.join(ra) #','.join(str(reversible_ages.keys()))


Code: Select all
age_swap()

enter your moms current age:   73

enter your current age:   37

for how long your mom's age do you want to theoretically want to compare age swap?:   200
Out[66]:
('No. of times that happens for is 1',
 '[[(15, 51), (26, 62), (37, 73), (48, 84), (59, 95)]]')
lovecodecakes
 
Posts: 56
Joined: Mon Feb 11, 2013 8:19 pm

Re: how to strip off from all the braces from a dict

Postby metulburr » Sat Apr 13, 2013 10:07 pm

Code: Select all
reversible_ages.setdefault('You:Mom', []).append([(baby,imom) for baby,imom in enumerate(xrange(mom_wen_uborn,expectancy)) if str(baby)[:]==str(imom)[::-1]])

your comp is so convoluted, i would rather not simplify it, and thus i dont know. you can just strip() off any char you want on a string.
Code: Select all
print(str(age_swap()[1]).strip('[').strip(']'))
New Users, Read This
version Python 3.3.2 and 2.7.5, tkinter 8.5, pyqt 4.8.4, pygame 1.9.2 pre
OS Ubuntu 14.04, Arch Linux, Gentoo, Windows 7/8
https://github.com/metulburr
User avatar
metulburr
 
Posts: 1116
Joined: Thu Feb 07, 2013 4:47 pm
Location: Elmira, NY

Re: how to strip off from all the braces from a dict

Postby Kebap » Sat Apr 13, 2013 10:10 pm

I think you may be going in the wrong direction. Python code is supposed to be extremely easily readable. Maybe check Pep8 for starters http://www.python.org/dev/peps/pep-0008/ and
> import this
Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!
Learn: How To Ask Questions The Smart Way
Join the #python-forum IRC channel on irc.freenode.net and chat with uns directly!
Kebap
 
Posts: 282
Joined: Thu Apr 04, 2013 1:17 pm
Location: Germany, Europe

Re: how to strip off from all the braces from a dict

Postby lovecodecakes » Sat Apr 13, 2013 10:14 pm

metulburr wrote:
Code: Select all
print(str(age_swap()[1]).strip('[').strip(']'))

O yes strip [ and ]..does sm kind of strip function work with dictionaries as well?
lovecodecakes
 
Posts: 56
Joined: Mon Feb 11, 2013 8:19 pm

Re: how to strip off from all the braces from a dict

Postby lovecodecakes » Sat Apr 13, 2013 10:20 pm

Kebap wrote:I think you may be going in the wrong direction. Python code is supposed to be extremely easily readable.

No the output is correct.code is fine.i crammed it as a comprehension. My problem is.to make it readable without paranthesis,special characters,etc. Only should return tuple values.
Q2: how to count like len() in 1 key for multiple values under 1 key.
lovecodecakes
 
Posts: 56
Joined: Mon Feb 11, 2013 8:19 pm

Re: how to strip off from all the braces from a dict

Postby Mekire » Sun Apr 14, 2013 4:49 am

lovecodecakes wrote:
Kebap wrote:I think you may be going in the wrong direction. Python code is supposed to be extremely easily readable.

No the output is correct.code is fine.i crammed it as a comprehension. My problem is.to make it readable without paranthesis,special characters,etc. Only should return tuple values.
Q2: how to count like len() in 1 key for multiple values under 1 key.


The fact that the output is correct has nothing to do with whether or not the code is fine. If you write horrible code and refuse to change people won't be very inclined to try and help you.

Code: Select all
dict.items()
will give you a list of (key,value) tuples if that helps. If you want to get the len of every sequence under each key in your dict, you will need to loop through it and find out. Trivial.

-Mek
User avatar
Mekire
 
Posts: 823
Joined: Thu Feb 07, 2013 11:33 pm
Location: Amakusa, Japan

Re: how to strip off from all the braces from a dict

Postby metulburr » Sun Apr 14, 2013 5:38 am

strip() is a str method. IF the value of a dictionary is a str then yes.
Code: Select all
>>> dicter = {'key':'value'}
>>> dicter['key'].strip('v')
'alue'


The problem is your code is so crammed in comp lists, almost unreadable, you will come back to it a year from now and have no idea what it does or why something might be wrong. So there could be a better way to doing what your doing, but no one is going to know to give it, because no one is dissecting your code, because of its complexity. So thus you might get an incorrect or lousy answer because its so complex, which we are trying to get the the best way to do something.
New Users, Read This
version Python 3.3.2 and 2.7.5, tkinter 8.5, pyqt 4.8.4, pygame 1.9.2 pre
OS Ubuntu 14.04, Arch Linux, Gentoo, Windows 7/8
https://github.com/metulburr
User avatar
metulburr
 
Posts: 1116
Joined: Thu Feb 07, 2013 4:47 pm
Location: Elmira, NY

Re: how to strip off from all the braces from a dict

Postby lovecodecakes » Sun Apr 14, 2013 12:53 pm

metulburr wrote:strip() is a str method. IF the value of a dictionary is a str then yes.
Code: Select all
>>> dicter = {'key':'value'}
>>> dicter['key'].strip('v')
'alue'


Tried that one. I see no other choice apart from not using dictionary while using it I would have to just iterate over to collect values and use smthg like [v.strip() for k,v in dicter.items()]
Thanks.
lovecodecakes
 
Posts: 56
Joined: Mon Feb 11, 2013 8:19 pm

Re: how to strip off from all the braces from a dict

Postby Mekire » Sun Apr 14, 2013 1:27 pm

...
What you are trying to do doesn't make sense, and that is the issue. If you want the (key,value) pairs as tuples for use as data then you don't need to strip anything. If however you just want to print the key,value pairs without parenthesis... you still don't need to strip anything. You just print using a proper print statement.

Code: Select all
mydict = {"a":1,"b":2,"c":3}

for pair in mydict.items():
    print(pair)

for k,v in mydict.items():
    print("{}:{}".format(k,v))
Output:
Code: Select all
('a', 1)
('c', 3)
('b', 2)
a:1
c:3
b:2


If you want the total length of every sequence in your dict, iterate and find it.
Code: Select all
mydict = {"a":[1,2,3],"b":[4,5,6,7],"c":[8,9]}

total_len = 0
for key in mydict:
    total_len += len(mydict[key])
print(total_len)
Output:
Code: Select all
9

So...um... what exactly is the problem?

Readability. Counts.
Code: Select all
def age_swap():
    moms_age = int(raw_input("Enter your mom's current age: "))
    your_age = int(raw_input("Enter your current age: "))
    expectancy = int(raw_input("How long would you like to compare ages?: "))

    ages = []
    mom_age_when_born = moms_age - your_age
    for baby_age in xrange(expectancy):
        mommy = mom_age_when_born+baby_age
        if str(baby_age) == str(mommy)[::-1]:
            ages.append((baby_age,mommy))
    return ages

def pretty(age_swap_data):
    print("\nYour Mother and you have had reversible ages {} times.".format(len(age_swap_data)))
    print("\nIt has happened at the ages:")
    for baby,mom in age_swap_data:
        print("\tYou: {} \tMother: {}".format(baby,mom))

if __name__ == "__main__":
    myages = age_swap()
    pretty(myages)
Output:
Code: Select all
Enter your mom's current age: 73
Enter your current age: 37
How long would you like to compare ages?: 200

Your Mother and you have had reversible ages 5 times.

It has happened at the ages:
   You: 15    Mother: 51
   You: 26    Mother: 62
   You: 37    Mother: 73
   You: 48    Mother: 84
   You: 59    Mother: 95

Don't try to stuff all your logic into one line just because you think it is clever. You would have received much better assistance if you had tried to write good code; rather than "clever" code.

-Mek
Last edited by Mekire on Sun Apr 14, 2013 2:13 pm, edited 1 time in total.
User avatar
Mekire
 
Posts: 823
Joined: Thu Feb 07, 2013 11:33 pm
Location: Amakusa, Japan

Re: how to strip off from all the braces from a dict

Postby lovecodecakes » Sun Apr 14, 2013 1:37 pm

Mekire wrote:...
What you are trying to do doesn't make sense, and that is the issue. If you want the (key,value) pairs as tuples for use as data then you don't need to strip anything. If however you just want to print the key,value pairs without parenthesis... you still don't need to strip anything. You just print using a proper print statement.

-Mek


I'll rephrase: The logic just checks for age swaps..like you're 73 and I am 37 while you gave me birth.so over a period of time, how many times such age swaps would happen? eg: 15:51, etc.. I was just simplifying it.. here it is, the code:

Code: Select all
def age_swap():
   reversible_ages={}
   moms_age=int(raw_input('enter your moms current age:\t'))
   baby_age=int(raw_input('enter your current age:\t'))
   expectancy=int(raw_input('for how long your mom\'s age do you want to theoretically want to compare age swap?:\t'))
   mom_wen_uborn=moms_age-baby_age
   for baby,imom in enumerate(xrange(mom_wen_uborn,expectancy)):
        if str(baby)[:]==str(imom)[::-1]:
            reversible_ages.setdefault('You:Mom', []).append(baby,imom)
   ra=[(''.join(str(v).strip())) for k,v in reversible_ages.iteritems()]
   count=len(ra) #count=len(list(reversible_ages))
   return 'No. of times that happens for is %s' %(count), ''.join(ra)


BUT, the Question is not related to this particular code.its with any code that returns in dictionary format.. Is there a way to stip down all the braces and just give values in a key, say in a tuple form and also how to count the number of values within a single key?
lovecodecakes
 
Posts: 56
Joined: Mon Feb 11, 2013 8:19 pm

Re: how to strip off from all the braces from a dict

Postby Mekire » Sun Apr 14, 2013 2:16 pm

Is there a way to stip down all the braces and just give values in a key, say in a tuple form

The question is obviated by the fact that it is almost never necessary to do so. Please see my above post again. I was editing it while you replied.

-Mek
User avatar
Mekire
 
Posts: 823
Joined: Thu Feb 07, 2013 11:33 pm
Location: Amakusa, Japan


Return to General Coding Help

Who is online

Users browsing this forum: Google [Bot] and 1 guest