Unpacking a tuple with dictionaries in Python - python

I have a tuple with multiple dictionaries and I wish to unpack them for further use.
Let's say I have this:
tuple_to_add = {'name': 'custom1', 'value': 'first value'},{'name': 'custom2', 'value': 'second value'}
And I'd like to iterate through them
I tried something like that but it didn't give me my answer:
for value, name in tuple_to_add:
print(value)
print(name)

Dictionaries can't be unpacked in a way tuples and lists can. If you had a tuple of tuples, your way of printing would work just fine:
tuple_to_add = ('custom1', 'first value'), ('custom2', 'second value')
for name, value in tuple_to_add:
# do whatever you want
You can simply iterate over the tuple and get the actual dictionary objects which you can use to get all the necessary information:
for dc in tuple_to_add:
print(dc['value'])
print(dc['name'])

Related

Update the first value of a dictionary

I have a list of multiple dictionaries.
The structure of my dictionaries are like that :
{'word': 'hello world', 'definition': 'saying hello to the world'}
I would like to update only the first value, so here 'hello world' in order to have it in upper case.
Here is my comprehension list i'm trying with:
upper = {key: value.upper()[0] for key, value in words_dict.items()}
The problem is that with this I have this result:
{'word': 'H', 'definition': 'S'}
I've tried loads of things but I'm still blocked...
A list comprehension is not very useful if all you want is to change the first item of the dict. You can change the dict in-place.
One way of doing it, without specifying the key name:
words_dict[next(iter(words_dict))] = words_dict[next(iter(words_dict))].upper()
You could do something like
upper = {key: words_dict[key].upper() if idx==0 else words_dict[key] for idx, key in enumerate(words_dict.keys())}
But using a dictionary comprehension here is hardly very readable. Perhaps a more readable approach would be to copy the dictionary and then just modify the first element.
upper = words_dict.copy()
first = list(upper.keys())[0]
upper[first] = upper[first].upper()
If you want to update the original dictionary, obviously operate on the original instead of on a copy.

How to append items from a list into a dictionary?

I'm very new to programming and Python and trying to figure things out. I'm trying to take items out of a list and append the keys and values to a dictionary but I can't figure out how. I tried using the dictionary's Update method but I'm only getting the last item from my list, not all the items. Here is my code:
a = {}
names = [ {'name': 'Bart'}, {'name': 'Lisa'}, {'name': 'Maggie'} ]
for name in names:
a.update(name)
The result I'm getting back is:
{'name': 'Maggie'}
But I want this in my new dictionary:
{'name': 'Bart'}, {'name': 'Lisa'}, {'name': 'Maggie'}
I wanted to put the items from the list inside the dictionary in order to access the values. I need all of the names but maybe there is a much easier way to do it.
Any hints would be great. Thanks.
With same key value you cant update a dict from list of dict. You can get a dict with key a list of values.
{'name': ['Bart', 'Lisa', 'Maggie']}
a={}
for n in names:
... for k in n:
... for k,v in [(k,n[k])]:
... if k not in a:a[k]=[v]
... else: a[k].append(v)

Ordering a nested dictionary in python

I have a nested dictionary (category and subcategories), dict, that I am having trouble sorting.
The output of dict is:
{u'sports': {u'basketball': {'name': u'Basketball', 'slug': u'basketball'}, u'baseball': {'name': u'Baseball', 'slug': u'baseball'}}, u'dance': {u'salsa': {'name': u'Salsa', 'slug': u'salsa'}}, u'arts': {u'other-5': {'name': u'Other', 'slug': u'other-5'}, u'painting': {'name': u'Painting', 'slug': u'painting'}}, u'music': {u'cello': {'name': u'Cello', 'slug': u'cello'}, u'accordion': {'name': u'Accordion', 'slug': u'accordion'}}}
How can I sort this dictionary so that the 'other' subcategory always shows up at the end of the nested dictionary. For example the order for the "arts" category should be:
..., u'arts': {u'painting': {'name': u'Painting', 'slug': u'painting'}, u'other-5': {'name': u'Other', 'slug': u'other-5'}}...
You have some major concept misunderstanding about dictionary. Dictionary in python is like a hash table, hash table has no order. The output of the dict is really environment dependent so you couldn't depend on that. You might see one way of the output while other people see another way. You should consider using OrderedDict instead.
Python dictionaries (regular dict instances) are not sorted. If you want to sort your dict, you could:
from collections import OrderedDict
mynewdict = OrderedDict(sorted(yourdict.items()))
An OrderedDict does not provide a sorting mechanism, but only respect the order of the keys being inserted on it (we sort those keys calling sorted beforehand).
Since you need a specific criteria (lets say your keys are alphabetically ordered except for the "other" key which goes to the end), you need to declare it:
def mycustomsort(key):
return (0 if key != 'other' else 1, key)
mynewdict = OrderedDict(sorted(yourdict.items(), key=mycustomsort))
This way you are creating a tuple for the nested criteria: the first criteria is other vs. no-other, and so the 0 or 1 (since 1 is greater, other comes later), while the second criteria is the key itself. You can remove the second criteria and not return a tuple if you want, but only the 0 and 1, and the code will work without alphabetical sort.
This solution will not work if you plan to edit the dictionary later, and there is no standard class supporting that.

Sorting list of dictionaries according to a certain key

runnerList = [{1:{"name":"John","height":173,"age":16}},
{2:{"name":"Fred","height":185,"age":18}},
{3:{"name":"Luke","height":181,"age":17}}]
I've been trying to sort this list of dictionaries in ascending order according to the age of the runners, with no success :( I tried:
import operator
runnerList.sort(key=lambda x: x['age'], reverse=True)
But nothing seemed to happen. How would i do this?
Try this:
runnerList.sort(key=lambda x: x.values()[0]['age'])
print runnerList
The reason you were getting an error is that your relevant dictionaries (those containing the age key) were also contained inside another dictionary. The solution was just as simple getting the values() of that external dict and getting grabbing the first element ([0]) which gave you the only dictionary contained inside.
Also, I removed the reverse=True used in your example. It would have given you the results in descending order and you specifically asked for them to be in ascending order.
Disclaimer:
If you're using a Python version >= 3:, you'd have to convert the generator object created with values().
runnerList.sort(key=lambda x: list(x.values())[0]['age'])
runnerList is list of dictionaries of dictionaries.
if you are sure that each list entry has only one pair of key-value, then you can sort by:
runnerList.sort(key=lambda x: list(x.values())[0]['age'], reverse=True)
if each list entry has more then one key-value pair, then you need to specify better the logic of your sort. what would you do on list like this?:
runnerList = [{1:{"name":"John","height":173,"age":16}},
{ 2:{"name":"Fred","height":185,"age":18},
4:{"name":"Fred","height":185,"age":13}
},
{3:{"name":"Luke","height":181,"age":17}}]
You basically have the runnerList in form of list as it is enclosed in []. First change it to dictionary like
runnerList = {1:{"name":"John","height":173,"age":16},
2:{"name":"Fred","height":185,"age":18},
3:{"name":"Luke","height":181,"age":17} }
and then you can import operator and can use the below function to sort the items and print it
sorted_runnerList = sorted(runnerList.items(),key=lambda x: x[1]['age'],)
While this would directly sort the age in the dictionary within the dictionary
So basically your function becomes
import operator
runnerList = {1:{"name":"John","height":173,"age":16},
2:{"name":"Fred","height":185,"age":18},
3:{"name":"Luke","height":181,"age":17} }
sorted_runnerList = sorted(runnerList.items(),key=lambda x: x[1]['age'],)
print sorted_runnerList
But do remember as we are using the .items() it would return immutable tuples
Output
[(1, {'age': 16, 'name': 'John', 'height': 173}), (3, {'age': 17, 'name': 'Luke', 'height': 181}), (2, {'age': 18, 'name
': 'Fred', 'height': 185})]

Python Dictionary - List Nesting

I have a dictionary with a key and a pair of values, the values are stored in a List. But i'm keeping the list empty so i can .append its values ,i cant seem to be able to do this
>>>myDict = {'Numbers':[]}
>>>myDict['Numbers'[1].append(user_inputs)
doesn't seem to work, returns an error . How do i refer to the list in myDict so i can append its values.
Also is it possible to have a dictionary inside a list and also have another list inside? if so? what is its syntax or can you recommend anyother way i can do this
>>>myDict2 = {'Names': [{'first name':[],'Second name':[]}]}
do i change the second nested list to a tuple?? Please lets keep it to PYTHON 2.7
You get an error because your syntax is wrong. The following appends to the list value for the 'Numbers' key:
myDict['Numbers'].append(user_inputs)
You can nest Python objects arbitrarily; your myDict2 syntax is entirely correct. Only the keys need to be immutable (so a tuple vs. a list), but your keys are all strings:
>>> myDict2 = {'Names': [{'first name':[],'Second name':[]}]}
>>> myDict2['Names']
[{'first name': [], 'Second name': []}]
>>> myDict2['Names'][0]
{'first name': [], 'Second name': []}
>>> myDict2['Names'][0]['first name']
[]
You should access the list with myDict['Numbers']:
>>>myDict['Numbers'].append(user_inputs)
You can have dicts inside of a list.
The only catch is that dictionary keys have to be immutable, so you can't have dicts or lists as keys.
You may want to look into the json library, which supports a mix of nested dictionaries and lists.
In addition, you may also be interested in the setdefault method of the dictionary class.
Format is something like:
new_dict = dict()
some_list = ['1', '2', '3', ...]
for idx, val in enumerate(some_list):
something = get_something(idx)
new_dict.setdefault(val, []).append(something)

Categories

Resources