Reputation: 429
How can I convert the below nested dictionary values to a single string ?
data = {'people': {'first': {'fname': 'P1', 'lname': 'L1'}, 'second': { 'fname': 'P2', 'lname': 'L2'}}}
Output should be P1 L1, P2 L2
Here is my current code:
print ', '.join("%s %s" % (data['people'][person].get('fname'), data['people'][person].get('lname')) for person in data['people'])
Is this a efficient way for a larger set to items in people dict ? If not how to improve this ?
Upvotes: 2
Views: 5318
Reputation: 251156
You can make your expression a bit short by only looping over just values and using named field in format string(Emphasis is to keep it more readable):
>>> print ', '.join("{fname} {lname}".format(**p) for p in data['people'].values())
P2 L2, P1 L1
In Python 3.2+ this can also be done using str.format_map
:
>>> print (', '.join("{fname} {lname}".format_map(p) for p in data['people'].values()))
P1 L1, P2 L2
If the keys fname
or lname
might be missing from the dicts then you could do something like this:
def get_values(dct, keys):
return (dct.get(k) for k in keys)
...
>>> keys = ('fname', 'lname')
>>> print ', '.join("{} {}".format(*get_values(p, keys)) for p in data['people'].values())
P2 L2, P1 L1
values()
with itervalues()
. In Python 3 use values()
only.P1 L1, P2
L2 here.Upvotes: 2
Reputation: 167
one = data['people']['second'].values()
two = data['people']['first'].values()
three = one + two
three.reverse()
for each in three:
print each,
I hope this what you are looking for.
Upvotes: 0
Reputation: 512
result = list()
for person in data["people"]:
for val in data["people"][person].values():
result.append(val)
result.append(", ")
result.pop()
print(' '.join(result))
or
result = list()
for person in data["people"]:
result.append(data["people"][person]["fname"])
result.append(data["people"][person]["lname"])
result.append(", ")
result.pop()
print(' '.join(result))
Upvotes: 0
Reputation: 135
Your data structure is recursive so you'll need a recursive function to obtain them
def get_values(data):
values = []
for k, v in data.items():
if isinstance(v, dict):
values.extend(get_values(v))
else:
values.append(v)
return values
Upvotes: 1
Reputation: 3244
data = {'people': {'first': {'fname': 'P1', 'lname': 'L1'}, 'second': { 'fname': 'P2', 'lname': 'L2'}}}
def myprint(d):
for k, v in d.iteritems():
if isinstance(v, dict):
myprint(v)
else:
print "{0} : {1}".format(k, v)
myprint(data)
Upvotes: -1