Reputation: 169
As I already asked on (Convert dictionary key tuple to string), but this time I have a dict={("name1","name2","name3"):256}
I want my dict to be dict={"name1,name2,name3":256}
but when I try this I get an error:
new_dct = {}
for k,v in dicts.items():
new_dct[','.join(k)] = v
**TypeError: sequence item 1: expected str instance, float found**
(i removed all nanS) Any idea?
Upvotes: 0
Views: 8676
Reputation: 1017
It's the same like before in Convert dictionary key tuple to string.
Just remove 's'
in dicts.items()
as in your first dict
variable or find another typo in your code espescially in element of dict
or dicts
. The exception (TypeError) could be cause by different reference to your dict
or dicts
variable. Others' answers already solved it, whether using dict comprehension:
dict = {("name1","name2","name3"):256}
new_dct = {','.join(key): value for key, value in dict.items()}
print(new_dct)
or normal for loop:
dict = {("name1","name2","name3"):256}
new_dct = {}
for key, value in dict.items():
new_dct[','.join(key)] = value
print(new_dct)
and the result will be same output.
{'name1,name2,name3': 256}
Upvotes: 0
Reputation: 9379
I tried your code with dict
renamed as d
and used in the loop in place of dicts
(the value of which is unclear), and it seems to work fine:
d={("name1","name2","name3"):256}
new_dct = {}
for k,v in d.items():
new_dct[','.join(k)] = v
print(new_dct)
Output:
{'name1,name2,name3': 256}
Here are a few notes:
dicts
without showing what value you assigned to it.dicts
using dicts={("name1", 2.0, "name3"):256}
, it would raise the exception you have mentioned (TypeError: sequence item 1: expected str instance, float found).str
, otherwise join()
may not work.Upvotes: 0
Reputation: 3624
Try this:
d = {("name1", "name2", "name3"): 256}
new_d = {','.join(map(str, k)): v for k, v in d.items()}
print(new_d) # {'name1,name2,name3': 256}
Upvotes: 3