473,499 Members | 1,727 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Just a quick one

Hi,

Just a quick one. I'm trying to call [Bob','One'] with this, but I keep
getting 'unhashable'. I've tried various ' " and [ and can't get the thing
to work. Any offers?

Thanks,

M

<code>

from random import *

Name_Number = xrange(int(raw_input("Choose number of Names (1-20)? ")))

state = [None,None]

nextName = {['Bob','One']:['Rita','Sue'],\
'Rita':['Mary','Sue',['Bob','One']],\
'Sue':['Rita','Mary',['Bob','One']],\
'Mary':['Sue','Rita']}

Name_List = []

tmp = choice((['Bob','One'],'Rita','Sue','Mary'))

for x in Name_Number:
print state
while tmp in state[0:2]:
tmp = choice(nextName[Name_List[-1]])
print tmp, ", ",
print
print "Name ",x+1," is ", tmp
Name_List.append(tmp)
state[x%2] = tmp

print Name_List

<code>
Jul 18 '05 #1
18 1668
"M. Clift" <no***@here.com> wrote in message
news:cg**********@news6.svr.pol.co.uk...
Hi,

Just a quick one. I'm trying to call [Bob','One'] with this, but I keep
getting 'unhashable'. I've tried various ' " and [ and can't get the thing
to work. Any offers?
....
nextName = {['Bob','One']:['Rita','Sue'],\
'Rita':['Mary','Sue',['Bob','One']],\
'Sue':['Rita','Mary',['Bob','One']],\
'Mary':['Sue','Rita']}


['Bob', 'One'] is a list.

You can't use a list as a dictionary key, because it is 'unhashable'.

Try ('Bob', 'One'), which is a tuple, instead.

See
http://www.python.org/doc/current/tu...00000000000000
(the first paragraph in 5.4).
--
I don't actually read my hotmail account, but you can replace hotmail with
excite if you really want to reach me.
Jul 18 '05 #2
lists cannot be used as dictionary keys (because lists are mutable, they
have no invariant hash value -> unhashable), use tuples instead:

nextName = {('Bob','One'):['Rita','Sue'],\
'Rita':['Mary','Sue',['Bob','One']],\
'Sue':['Rita','Mary',['Bob','One']],\
'Mary':['Sue','Rita']}

M. Clift wrote:
Hi,

Just a quick one. I'm trying to call [Bob','One'] with this, but I keep
getting 'unhashable'. I've tried various ' " and [ and can't get the thing
to work. Any offers?

Thanks,

M

<code>

from random import *

Name_Number = xrange(int(raw_input("Choose number of Names (1-20)? ")))

state = [None,None]

nextName = {['Bob','One']:['Rita','Sue'],\
'Rita':['Mary','Sue',['Bob','One']],\
'Sue':['Rita','Mary',['Bob','One']],\
'Mary':['Sue','Rita']}

Name_List = []

tmp = choice((['Bob','One'],'Rita','Sue','Mary'))

for x in Name_Number:
print state
while tmp in state[0:2]:
tmp = choice(nextName[Name_List[-1]])
print tmp, ", ",
print
print "Name ",x+1," is ", tmp
Name_List.append(tmp)
state[x%2] = tmp

print Name_List

<code>

Jul 18 '05 #3
Hi Benjamin,

Thanks, that was quick!

How would I print just 'Bob' if the result was
'[('Bob',One'),('Mary','Spam')] ? As print Name_List[0] obviously gives
('Bob','One')

M
Jul 18 '05 #4
Hi Benjamin,

Sorry, another question. How do I remove the brackets form the list?
Name_List.remove('(') doesn't work.

Thanks,

M
Jul 18 '05 #5
"M. Clift" <no***@here.com> wrote in message
news:cg**********@news5.svr.pol.co.uk...
Hi Benjamin,

Thanks, that was quick!

How would I print just 'Bob' if the result was
'[('Bob',One'),('Mary','Spam')] ? As print Name_List[0] obviously gives
('Bob','One')

M


Name_List[0][0]

Jul 18 '05 #6
Hi Paul,

Thanks for that. Would you know how to remove the brackets or how to convert
it to a list such as 'Bob', 'Mary' etc...

M
Jul 18 '05 #7
"M. Clift" <no***@here.com> wrote in message news:<cg**********@news7.svr.pol.co.uk>...
Hi Benjamin,

Sorry, another question. How do I remove the brackets form the list?
Name_List.remove('(') doesn't work.


The brackets or parentheses are not part of the list or tuple, they
are part of the string representation of the list or tuple.

If you want to turn the list ('Bob', 'Mary') into the string 'Bob,
Mary', use:

', '.join(('Bob', 'Mary'))

-infi
Jul 18 '05 #8
SM
"M. Clift" <no***@here.com> wrote in message news:<cg**********@news7.svr.pol.co.uk>...
Sorry, another question. How do I remove the brackets form the list?
Name_List.remove('(') doesn't work.


The parentheses or brackets are not "in" the tuple or list. They are
used in the representation of tuples or lists. The tuple ('Bob',
'Mary') consists of two objects, the string "Bob" and the string
"Mary". But when we describe a tuple using the canonical notation, we
put parentheses around the elements, and we put commas between them.
Those are part of the representation, not part of the tuple.
(Likewise, when I say 'the string "Bob" and the string "Mary"', the
double quote marks around each name are not part of the string, they
are part of how you represent a string.)

If you want to remove parentheses and commas from printing a tuple,
then don't print the whole tuple, but loop through it and print each
element.
Jul 18 '05 #9
A tuple (actually, any iterable) can be converted to a list by using
list(), like so:

list( (1, 2, 3) ) ==> [1, 2, 3]

In fact, most types can be converted like so, str(), list(), dict(),
tuple(). You can always do "help(str)" in Python for more verbose
information.

On Wed, Aug 25, 2004 at 03:00:11PM +0100, M. Clift wrote:
Hi Benjamin,

Sorry, another question. How do I remove the brackets form the list?
Name_List.remove('(') doesn't work.

Thanks,

M

Jul 18 '05 #10
Hi SM and Phil ,

Thankyou both for your help.

M
Jul 18 '05 #11
Hi All,

At the risk of looking stupid would someone mind showing me how this is done
in this case. I can't remove the brackets from (('Bob', 'Mary'), ('Spam',
'chips')) to give(('Bob', 'Mary', 'Spam', 'chips')) . From what Phil and Sm
said I thought it would be easy. I've tried using list( ). I've had a go at
referencing the individual elements...

Anyone?

Thanks
M
Jul 18 '05 #12
On Thu, 26 Aug 2004 04:06:33 +0100, "M. Clift" <no***@here.com>
declaimed the following in comp.lang.python:
Hi All,

At the risk of looking stupid would someone mind showing me how this is done
in this case. I can't remove the brackets from (('Bob', 'Mary'), ('Spam',
'chips')) to give(('Bob', 'Mary', 'Spam', 'chips')) . From what Phil and Sm
said I thought it would be easy. I've tried using list( ). I've had a go at
referencing the individual elements...
You have a tuple of TWO tuples... Operations such as list() work
on the top level, not the sublevels within that level.
t2 = ( ("Bob", "Mary"), ("Spam", "Beans") )
t2 (('Bob', 'Mary'), ('Spam', 'Beans')) l1 = []
for i in t2: .... for j in list(i):
.... l1.append(j)
.... l1 ['Bob', 'Mary', 'Spam', 'Beans'] " ".join(l1) 'Bob Mary Spam Beans'


If you expect multiple levels of nesting, you may wish to create
a recursive function (or a generator?) to traverse the
tuple/list/sequence and build a single list from it.

-- ================================================== ============ <
wl*****@ix.netcom.com | Wulfraed Dennis Lee Bieber KD6MOG <
wu******@dm.net | Bestiaria Support Staff <
================================================== ============ <
Home Page: <http://www.dm.net/~wulfraed/> <
Overflow Page: <http://wlfraed.home.netcom.com/> <

Jul 18 '05 #13
M. Clift wrote:
Hi All,

At the risk of looking stupid would someone mind showing me how this is done
in this case. I can't remove the brackets from (('Bob', 'Mary'), ('Spam',
'chips')) to give(('Bob', 'Mary', 'Spam', 'chips')) . From what Phil and Sm
said I thought it would be easy. I've tried using list( ). I've had a go at
referencing the individual elements...

Anyone?

Thanks
M


I don't think you are truly understanding what the parentheses and
brackets are. How about an analogy? You have $5.34 in your pocket. Now,
you don't actually have a dollar sign in your pocket. Or a decimal
point. Those symbols are just used when you want to display the the
amount of money you have. The brackets are only used to help display
what is in the list. They aren't a part of the list that can be removed.
So, your question is similar to asking "I have $5.35 in my pocket. How
do I remove the dollar sign?"

Does that make sense?

So, are you just trying to change how your list is displayed on the
screen (or printer or whatever) or do you actually want to change your
list? I'll assume you want to change your list. I'll use tuples instead
of lists, though, since you want to use them as dictionary keys. So we
have this:
a = ('Bob', 'Mary')
b = ('Spam', 'chips')
c = (a, b)
c (('Bob', 'Mary'), ('Spam', 'chips'))

First we need to create a list, not a tuple, so we can modify it.
extend() is a list method that slaps a sequence on to the end of the list.
c = []
c.extend(a)
c ['Bob', 'Mary'] c.extend(b)
c

['Bob', 'Mary', 'Spam', 'chips']

What we're doing here is called flattening a list. The ASPN Cookbook[1]
has a more general method for flattening. It uses a flatten() method.
Use it like this:

def flatten(*args):
for arg in args:
if type(arg) in (type(()),type([])):
for elem in arg:
for f in flatten(elem):
yield f
else: yield arg

c = (('Bob', 'Mary'), ('Spam', 'chips'))
c = flatten(c)
print list(c)

This prints out:

['Bob', 'Mary', 'Spam', 'chips']
Hope this helps.
Greg

[1]http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/121294

Jul 18 '05 #14
M. Clift wrote:
At the risk of looking stupid would someone mind showing me how this is done
in this case. I can't remove the brackets from (('Bob', 'Mary'), ('Spam',
'chips')) to give(('Bob', 'Mary', 'Spam', 'chips')) . From what Phil and Sm
said I thought it would be easy. I've tried using list( ). I've had a go at
referencing the individual elements...


Noodle around with IDLE (if using windows it should be in your python
group). It's a great way to play with this stuff.
stuff = (('Bob', 'Mary'), ('Spam', 'chips'))
Hmmm - what is stuff?
type(stuff) <type 'tuple'>

I see. How big is it?
len(stuff) 2

Ah ... so ...
stuff[0] ('Bob', 'Mary') stuff[1] ('Spam', 'chips')

So in that case
morestuff = stuff[0]+stuff[1]
morestuff ('Bob', 'Mary', 'Spam', 'chips') type(morestuff) <type 'tuple'> evenmorestuff = list(morestuff)
evenmorestuff ['Bob', 'Mary', 'Spam', 'chips'] type(evenmorestuff) <type 'list'>

Well - it got rid of your brackets. But was it what you wanted? Maybe
you actually now want.
stringstuff = ', '.join(morestuff)
stringstuff 'Bob, Mary, Spam, chips' type(stringstuff)

<type 'str'>

Hmmm - getting quite stuff'y in here isn't it? :)

Ian
Jul 18 '05 #15
Hi to all of you,

Well that's a lot of 'stuff' you gave me. Thankyou.

I did understand that the brackets were not part of the list, but leaving
them that way (as tuples) I could see problems in trying to refer to them at
some stage. I was having no luck with what I was doing, ending up with just
being able to call the first item in each tuple. As I'm new to this, maybe I
don't actually need to do this in the long run for what I want, but for now
while I think that I do, these answers are exactly what I need.

All the best,

M
Jul 18 '05 #16
"M. Clift" <no***@here.com> writes:
Hi to all of you,

Well that's a lot of 'stuff' you gave me. Thankyou.

I did understand that the brackets were not part of the list, but leaving
them that way (as tuples) I could see problems in trying to refer to them at
some stage. I was having no luck with what I was doing, ending up with just
being able to call the first item in each tuple. As I'm new to this, maybe I
don't actually need to do this in the long run for what I want, but for now
while I think that I do, these answers are exactly what I need.

All the best,

M


Did anyone explain list "flattening"? That may be what you want.

http://aspn.activestate.com/ASPN/Coo.../Recipe/121294

--
ha************@boeing.com
6-6M21 BCA CompArch Design Engineering
Phone: (425) 342-0007
Jul 18 '05 #17
On Thu, 26 Aug 2004 04:27:18 GMT, Greg Krohn <gr**@invalid.invalid>
declaimed the following in comp.lang.python:
>>> c.extend(a)

Ah, the missing link in my attempts <G>

def flatten(*args):
for arg in args:
if type(arg) in (type(()),type([])):
for elem in arg:
for f in flatten(elem):
yield f
else: yield arg
And the other missing item -- since I've not used generators
before. I was sure a generator could be used, but the actual form was a
bit beyond me at that time of night...
So... one more message into my archives... Thanks for the
samples (even though I'm not the original querant).

-- ================================================== ============ <
wl*****@ix.netcom.com | Wulfraed Dennis Lee Bieber KD6MOG <
wu******@dm.net | Bestiaria Support Staff <
================================================== ============ <
Home Page: <http://www.dm.net/~wulfraed/> <
Overflow Page: <http://wlfraed.home.netcom.com/> <

Jul 18 '05 #18
Hi,

Thanks for the link.

M
Jul 18 '05 #19

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

8
5359
by: Dutchy | last post by:
Dear reader, In an attempt to obtain the path to the quick-launch-folder in order to create a shortcut to my application-updates during installation , I thought to: 1- check if quick launch...
2
1766
by: A.M | last post by:
Hi, I uderstand any Quick Start samples in .NET documentation or VS.NET documentation or in any other community/portal websites, is a link to http://samples.gotdotnet.com/quickstart/. That...
1
4516
by: DILA | last post by:
Hi, I have included an embedded Real Player and an embedded Quick Time Player for streaming videos, in my web pages. I'm interested in searching for a method or a script to disable the...
3
2532
by: homec | last post by:
Hi, I have included an embedded Real Player and an embedded Quick Time Player for streaming videos, in my web pages. I'm interested in searching for a method or a script to disable the ...
0
7128
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
7169
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
1
6892
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
7385
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
1
4917
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...
0
4597
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and...
0
3088
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
661
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
294
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.