Multimapping and string converting

Gabriel Genellina gagsl-py2 at yahoo.com.ar
Fri Sep 19 17:56:24 CEST 2008


En Fri, 19 Sep 2008 10:59:26 -0300, Ron Brennan <brennan.ron at gmail.com>  
escribió:

> Hello,
>
> I have a multimap dictionary with a 1 Key to N values.  I want to convert
> the N values to a string to be used elsewhere in my program.
>
> So I have dict[(1,[1, 2 ,3 ,4])] which I have sorted
>
> When I do a print ''.join(str(dict.value())) I get [1, 2, 3, 4] as an  
> output
> when I really want 1 2 3 4
>
> Here is my code:
>
> dmapItems = dictionary.items()
> dmapItems.sort()
>
> for tcKey, tcValue in dmapItems:
>     file.write('Key = %s\nValue = %s" % (tcKey, tcValue)
>
> stinger = ''.join(str(tcValue))
>
> print stringer
>
> The Output = [145, 2345, 567, 898]
> I need it to be 145 2345 567 898

I guess you probably tried using ' '.join(value) and got an error like  
this:
TypeError: sequence item 0: expected string, int found
so you inserted that str(...), but you don't still get what you want.
You want "145 2345 567 898". *If* you had a list like this: value =  
["145", "2345", "567", "898"] (that is, a list of strings) *then* '  
'.join(value) would do what you want. But you have this to start with  
instead: value = [145, 2345, 567, 898] (a list of numbers), how to convert  
it into a list of strings?
str(value) returns a single string that "looks like" a list but isn't:  
"[145, 2345, 567, 898]". Instead, you need to convert each element  
individually, and keep them in a list. Try this:
value = [str(elem) for elem in value]
Also, I'd use sorted() to iterate over all items. PUtting all together:

for tcKey, tcValue in sorted(dictionary.items()):
     values = [str(elem) for elem in tcValue]
     values = ' '.join(values)
     print tcKey, values

or perhaps:

for tcKey, tcValue in sorted(find_a_good_name_for_me.iteritems()):
     values_str = ' '.join(str(elem) for elem in tcValue)
     print tcKey, values_str

(using lazy objects (iteritems and a generator expression) instead of  
concrete lists)

-- 
Gabriel Genellina




More information about the Python-list mailing list