the output for the code:
dict={k:v for k in range(1,4) for v in range(1,3) }
print(dict)
out put is:
{1: 2, 2: 2, 3: 2}
but thought the output should be:
{1: 1, 2: 1, 3: 1}
why is it taking 2 for the value of v.
Python lets you use the same key multiple times in a dictionary comprehension, but obviously the final dictionary can only contain the key once. The associated value is the last one you specified, as per the Python reference manual, 6.2.7 Dictionary Displays:
When the comprehension is run, the resulting key and value elements are inserted in the new dictionary in the order they are produced.
Is there an easy way to reorder a list of values in a dictionary alphabetically while keeping the order of the keys the same? I'm not looking to sort the dictionary by values just alphabetically order the lists of them. Thanks
Assuming you just didn't care about the old data ordering, you could just run this function:
def alphabetizeDictValues(dictionary):
for key in dictionary:
dictionary[key].sort()
The sort function of a list sorts the list in-place (making it lossy), so this would only work if you didn't care about the old ordering. This means that the memory requirement is lower, but also means you don't have a reference to how your list was previously sorted. Alternatively, if you wanted to save the old ordering, you could create this function
def alphabetizeDictValues(dictionary):
dupeDictionary = {}
for key in dictionary:
oldLst = list(dictionary[key])
dupeDictionary[key] = oldLst
dictionary[key].sort()
return dupeDictionary
This would return a copy of the input dictionary (with lists not sorted) while the dictionary you passed in would be the sorted version.
Assuming you want to sort the values independently of the keys (which can change the key: value association), you can create a new dictionary:
d = {'b': 1, 'c': 0, 'a': 2}
d2 = dict(zip(d, sorted(d.values())))
Output: {'b': 0, 'c': 1, 'a': 2}
Maybe I'm overthinking this and you just want:
sorted(d.values())
# [0, 1, 2]
I know that there are a bunch of ways to make a dictionary out of two lists, but I wanted to do it using two FOR loops to iterate over both lists. Therefore, I used the following code. Surprisingly, the code doesn't iterate over the second list that contains the values of the dictionary keys and only considers the last element of the list as the value.
key = ['hello', 'mello', 'vello']
value = [1, 2, 3]
dictionary = {k: v for k in key for v in value}
print('dictionary is ', dictionary)
the result was:
dictionary is: {'hello': 3, 'mello': 3, 'vello': 3}
But I expect that the result would be:
dictionary is: {'hello': 1, 'mello': 2, 'vello': 3}
I appreciate it if anyone can clarify this for me.
My understanding is the full dictionary is being recreated each loop with each number as the key, resulting in only your final output being that of the last value (best shown by reversing your key and value statements, returning {1: 'vello', 2: 'vello', 3: 'vello', 4: 'vello'}
If the other is your intended output, this should work fine:
dictionary = dict(zip(key,value))
You can use zip for this purpose.
dictionary = dict(zip(keys, values))
This question already has answers here:
switching keys and values in a dictionary in python [duplicate]
(10 answers)
Closed 6 years ago.
I am currently preparing for a python exam and one topic we are expected to understand is having to flip a dictionary in which values become the keys and the keys become values. I am confused as to what this asking and if someone could provide me with a basic example to see what it looks like I would greatly appreciate it.
Simply write a dict comprehension expression and make it's key as value and values as key. For example:
>>> my_dict = {1: 2, 3: 4, 5: 6}
>>> {value: key for key, value in my_dict.items()}
{2: 1, 4: 3, 6: 5}
Note: Since, dict contains unique keys. In case you have same element as value for multiple keys in your original dict, you will loose related entries. For example:
# Same values v v
>>> my_dict = {1: 2, 3: 4, 5: 2}
>>> {value: key for key, value in my_dict.items()}
{2: 5, 4: 3}
#^ Only one entry of `2` as key
Let us consider a dictionary:
sample_dict={1:'r099',2:'g444',3:'t555',4:'f444',5:'h666'}
I want to re-order this dictionary in an order specified by a list containing the order of the dictionary keys that I desire. Let us say the desired order list is:
desired_order_list=[5,2,4,3,1]
So, I want my dictionary to appear like this:
{5:'h666',2:'g444',4:'f444',3:'t555',1:'r099'}
If I can get a list of values that is fine too. Meaning, the result can be this:
['h666','g444','f444','t555','r099']
How do I achieve this in the least complex way possible?
Answer for Python 3.6+
Guido has assured dictionaries would be ordered from Python 3.7 onwards, and they already were as an experimental feature in 3.6. The answer has already been expanded on in Fastest way to sort a python 3.7+ dictionary.
In this case, building a new dict with simple dictionary comprehension based on the items contained in the desired_order_list will do the trick.
sample_dict = {1: 'r099', 2: 'g444', 3: 't555', 4: 'f444', 5: 'h666'}
print(sample_dict)
>>> {1: 'r099', 2: 'g444', 3: 't555', 4: 'f444', 5: 'h666'}
desired_order_list = [5, 2, 4, 3, 1]
reordered_dict = {k: sample_dict[k] for k in desired_order_list}
print(reordered_dict)
>>> {5: 'h666', 2: 'g444', 4: 'f444', 3: 't555', 1: 'r099'}
If you're using an OrderedDict, you can do
for key in [5,2,4,3,1]:
my_ordered_dict[key] = my_ordered_dict.pop(key)
This reinserts everything in your ordered dict in the sequence you want, such that later you can do
my_ordered_dict.values()
And get the list you suggested in the question.
If you wrap the reinsertion in a try: ...; except KeyError: pass, you can reorder an OrderedDict even if not all the keys in your list are present.
Python dictionaries are unordered.
Use OrderedDict instead.
Using an OrderedDict or Eli's solution will probably be a good way to go, but for reference here is a simple way to obtain the list of values you want:
[sample_dict[k] for k in desired_order_list]
If you aren't completely sure that every element from desired_order_list will be a key in sample_dict, use either [sample_dict.get(k) ...] or [... for k in desired_order_list if k in sample_dict]. The first method will put None in for missing keys, the second method will only include values from the keys are are in the dict.
What is the meaning of reordering the dictionary for you? Dictionaries are unordered data structures by their nature - they are used for lookup rather than order.
Do you want to iterate over the dictionary in some specific order? Then just use your desired_order_list:
for key in desired_order_list:
# d is the dictionary
# do stuff with d[key]
As others have mentioned, Python has an OrderedDict (in 2.7 or 3.x), but I don't think it's what you need here. "Reordering" it is just too inefficient. It's much better to just carry your dictionary along with the list of keys in desired order, together.
If you still insist on an OrderedDict, just create a new OrderedDict, inserting the value into it in the order of desired_order_list.
The existing answers more than cover the question except in the special case when the list is incomplete and we want to keep all the values leaving all the rest in the end: Then, after creating the dictionary, update it with the old one to add the missing values:
sample_dict = {1: 'r099', 2: 'g444', 3: 't555', 4: 'f444', 5: 'h666'}
print(reordered_dict)
# {1: 'r099', 2: 'g444', 3: 't555', 4: 'f444', 5: 'h666'}
desired_order_list = [5, 2 ]
reordered_dict = {k: sample_dict[k] for k in desired_order_list}
print(reordered_dict)
# {5: 'h666', 2: 'g444'}
reordered_dict.update(sample_dict)
print(reordered_dict)
# {5: 'h666', 2: 'g444', 1: 'r099', 3: 't555', 4: 'f444'}
wouldn't be easier just doing this way?
sample_dict={1:'r099',2:'g444',3:'t555',4:'f444',5:'h666'}
new_sample_dict={
1: sample_dict[5],
2: sample_dict[2],
3: sample_dict[4],
4: sample_dict[3],
5: sample_dict[1]
}
Use SortedDict provided by django (from django.utils.datastructures import SortedDict). SortedDict stores it's order in keyOrder attribute (which is just a list, so you can reorder it any way you like, anytime).
If you don't have django installed or have no use for django, just lift the implementation django.utils.datatstructures. It doesn't depend on any other parts of django.