Skip to content

Commit 63d7bc3

Browse files
committed
as_dict() takes an argument to hide empty attributes
1 parent 73e6934 commit 63d7bc3

1 file changed

Lines changed: 22 additions & 3 deletions

File tree

nameparser/parser.py

Lines changed: 22 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -134,11 +134,30 @@ def __repr__(self):
134134
'nickname': self.nickname,
135135
}
136136

137-
def as_dict(self):
138-
"""Return the parsed name as a dictionary of its attributes."""
137+
def as_dict(self, include_empty=True):
138+
"""
139+
Return the parsed name as a dictionary of its attributes.
140+
141+
:param bool include_empty: Include keys in the dictionary for empty name attributes.
142+
:rtype: dict
143+
144+
.. doctest::
145+
146+
>>> name = HumanName("Bob Dole")
147+
>>> name.as_dict()
148+
{u'last': u'Dole', u'suffix': u'', u'title': u'', u'middle': u'', u'nickname': u'', u'first': u'Bob'}
149+
>>> name.as_dict(False)
150+
{u'last': u'Dole', u'first': u'Bob'}
151+
152+
"""
139153
d = {}
140154
for m in self._members:
141-
d[m] = getattr(self, m)
155+
if include_empty:
156+
d[m] = getattr(self, m)
157+
else:
158+
val = getattr(self, m)
159+
if val:
160+
d[m] = val
142161
return d
143162

144163
### attributes

0 commit comments

Comments
 (0)