0

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']
mvee
  • 263
  • 2
  • 15
  • @DeepSpace please do not close this question without reading it through - you can see in my question here that I have attempted to use decode as mentioned in the associated answer you linked this to, however it is not working correctly in my case. – mvee Jan 06 '20 at 12:13
  • Just do this inside your for loop of your class: `value_list = [v.decode('utf-8') for v in dictionary[key]];setattr(self, key, value_list)` remove everything else. You were using decode, but not using or storing the decoded part. – Sayandip Dutta Jan 06 '20 at 12:16

1 Answers1

1

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')).

adnanmuttaleb
  • 3,388
  • 1
  • 29
  • 46