英文:
Python - Decoding dictionary value List<bytes> to List<String> without "b" notation
问题
Application.py:
from Person import Person
person = {
'firstName': [b'Foo'],
'lastName': [b'Bar'],
'email': [
b'foo.bar@example.com',
b'bar.foo@example.com',
],
}
p = Person(person)
print(p.firstName)
print(p.lastName)
print(p.email)
Person.py:
class Person(object):
def __init__(self, dictionary):
for key in dictionary:
value_list = dictionary[key]
for i in range(len(value_list)):
value_list[i] = value_list[i].decode('utf-8')
setattr(self, key, value_list)
Running Application.py outputs this:
['Foo']
['Bar']
['foo.bar@example.com', 'bar.foo@example.com']
英文:
Novice Python (3.7) question here - I'm attempting to decode a Python dictionary's keys which are represented as lists of byte objects to a class but am seeing that the byte notation is not being removed as a part of decoding.
Can anyone help me achieve this without just bolting on something like v.replace("b", "")?
Application.py
from Person import Person
person = {
'firstName': [b'Foo'],
'lastName': [b'Bar'],
'email': [
b'foo.bar@example.com',
b'bar.foo@example.com',
],
}
p = Person(person)
print(p.firstName)
print(p.lastName)
print(p.email)
Person.py
class Person(object):
def __init__(self, dictionary):
for key in dictionary:
value_list = dictionary[key]
for v in value_list:
v.decode('utf-8')
setattr(self, key, dictionary[key])
Running Application.py outputs this
[b'Foo']
[b'Bar']
[b'foo.bar@example.com', b'bar.foo@example.com']
But I require this (without "b'" notation)
['Foo']
['Bar']
['foo.bar@example.com', 'bar.foo@example.com']
答案1
得分: 1
以下是翻译好的代码部分:
class Person(object):
def __init__(self, dictionary):
for key, values in dictionary.items():
try:
new_values = []
for value in values:
new_values.append(value.decode('utf-8'))
setattr(self, key, new_values)
except:
setattr(self, key, values.decode('utf-8'))
person = {
'firstName': ['Foo'],
'lastName': ['Bar'],
'email': [
'foo.bar@example.com',
'bar.foo@example.com',
],
}
p = Person(person)
print(p.firstName)
print(p.lastName)
print(p.email)
输出:
['Foo']
['Bar']
['foo.bar@example.com', 'bar.foo@example.com']
注意:你的错误在于在setattr
中使用原始值(dictionary[key]
)而不是解码后的值(value.decode('utf-8')
)。
英文:
Try this:
class Person(object):
def __init__(self, dictionary):
for key, values in dictionary.items():
try:
new_values = []
for value in values:
new_values.append(value.decode('utf-8'))
setattr(self, key, new_values)
except:
setattr(self, key, values.decode('utf-8'))
person = {
'firstName': [b'Foo'],
'lastName': [b'Bar'],
'email': [
b'foo.bar@example.com',
b'bar.foo@example.com',
],
}
p = Person(person)
print(p.firstName)
print(p.lastName)
print(p.email)
Output:
['Foo']
['Bar']
['foo.bar@example.com', 'bar.foo@example.com']
Note: your mistake is that you are using the original value ( dictionary[key]
) in setattr
not the decoded one (value.decode('utf-8')
).
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论