This question already has answers here:
How do you find the first key in a dictionary?
(12 answers)
Closed 2 years ago.
I am trying to get the first item I inserted in my dictionary (which hasn't been re-ordered).
For instance:
_dict = {'a':1, 'b':2, 'c':3}
I would like to get the tuple ('a',1)
How can I do that?
Before Python 3.6, dictionaries were un-ordered, therefore "first" was not well defined. If you wanted to keep the insertion order, you would have to use an OrderedDict: https://docs.python.org/2/library/collections.html#collections.OrderedDict
Starting from Python 3.6, the dictionaries keep the insertion order by default ( see How to keep keys/values in same order as declared? )
Knowing this, you just need to do
first_element = next(iter(_dict.items()))
Note that since _dict.items() is not an iterator but is iterable, you need to make an iterator for it by calling iter.
The same can be done with keys and values:
first_key = next(iter(_dict))
first_value = next(iter(_dict.values()))
Related
This question already has answers here:
How to iterate over a python list?
(4 answers)
Closed 3 years ago.
I am trying to write a function in Python 3.6 that returns the content of a dictionary as a list, sorted according to the key in descending order.
Example test cases are as follows:
Inputs: {'y':1, 'z':1, 'x':1} | {3:['x','y'], 100:['z']}
Desired Outputs: [{'z':1},{'y':1},{'x':1}] | [{100:['z']}, {3:['x', 'y']}]
def sorted_dict_content(key_val):
# create an empty list
key_itemList = []
# for each key in sorted list of keys of key_val:
# append the key-value pair to key_itemList
for i in key_val:
key_itemList[key_val[i]].append(i)
sorted(key_val.key(), reverse=True)
return key_itemList
However, when I run the program I am getting IndexError: list index out of range. I also have not had luck with sorted().
Thanks for the help.
Trying to assign to the list via list[something] = something else will try to acces the list at the something-index not extend the list by adding the something-index, unlike a dict's behaviour. The correct way to append the key-value-pair to the list would be
key_ItemList.append({key_val[i]:i})
This question already has answers here:
How to keep keys/values in same order as declared?
(13 answers)
Closed 4 years ago.
I have a dictionary with key values, But I want to rearrange/change the type of the keys/values in the dict so as per my like. How can I do it?
for Example:
Dict = {'a':19,'b':30, 'c':"New", 'd': 6}
I want to make b as key at position 1 and/or I want to make a key as a list and so on.
NOTE: I dont not want to sort the dict! But decide myself :
Example:
If this key is present in dict then put this Key,value in Position 1
So my final result would be,
Dict = {'b':30, 'a':[19], 'd':6, 'c':"new"}
You can't put the key b in position 1, or any position. Dictionaries are unordered in principle. There is usually not much reason to care about the order.
But if you do care about the order then you have to maintain it yourself outside of the dict that holds your data. You can't insist on the dict maintaining the order itself, because dicts don't work that way. For example:
orderby = ["b", "a", "d", "c"]
for key in orderby:
do_something_with(key, Dict[key])
To change the order, for example to exchange the positions of "a" and "b":
orderby[0],orderby[1] = orderby[1],orderby[0]
There is also an OrderedDict in collections, but that is mainly to remember the order that things were added to it, which doesn't seem to be what you want.
To change the value associated with 'a' just assign it:
Dict['a'] = [19]
The rearranging I think you cannot do as dictionaries are not ordered structures. The second one you can simply do by:
Dict['a'] = list(Dict['a'])
This question already has answers here:
How do I sort a dictionary by key?
(32 answers)
Closed 7 years ago.
Let's say I have two dictionaries, one with a set of data and another with the same keys but I want to filter and clean up the data. To be more specific, please take a look at this example of runner's distances:
dict1:{'Bob':'1 mile', 'Barbara':'200 feet', 'Sue':'250 feet'}
dict2:{'Bob':'','Barbara':'','Sue':''}
I would like to strip the value string from each key's value (i.e., the words "mile" and "feet"). I would also like to convert "miles" to "feet" to make sure all units are in feet.
I tried doing a loop such as
for key,val in dict1.items():
if "mile" in val:
dict2[key] = float(val[:-6]) * 5280
else:
dict2[key] = float(val[:-6]
Unfortunately, while the logic is right, a dictionary is unsorted so it ends up giving me something like:
dict2 = {'Barbara':5280, 'Bob':200, 'Sue':250}
I'd like to know if there is a method to sort both dictionaries (not in alphabetical order or numerical order, but in the order I originally assigned) so that it actually assigns the intended value for each key?
The keys of a dictionary aren't stored in any particular order; you are free to sort the keys externally any time you wish. Your code is assigning the right values to the right keys.
This question already has answers here:
How can I make a dictionary (dict) from separate lists of keys and values?
(21 answers)
Closed 4 years ago.
I have read this link
But how do I initialize the dictionary as well ?
say two list
keys = ['a','b','c','d']
values = [1,2,3,4]
dict = {}
I want initialize dict with keys & values
d = dict(zip(keys, values))
(Please don't call your dict dict, that's a built-in name.)
In Python 2.7 and python 3, you can also make a dictionary comprehension
d = {key:value for key, value in zip(keys, values)}
Although a little verbose, I found it more clear, as you clearly see the relationship.
This question already has answers here:
How can I get a sorted copy of a list?
(2 answers)
Closed 28 days ago.
The list sort() method is a modifier function that returns None.
So if I want to iterate through all of the keys in a dictionary I cannot do:
for k in somedictionary.keys().sort():
dosomething()
Instead, I must:
keys = somedictionary.keys()
keys.sort()
for k in keys:
dosomething()
Is there a pretty way to iterate through these keys in sorted order without having to break it up in to multiple steps?
for k in sorted(somedictionary.keys()):
doSomething(k)
Note that you can also get all of the keys and values sorted by keys like this:
for k, v in sorted(somedictionary.iteritems()):
doSomething(k, v)
Can I answer my own question?
I have just discovered the handy function "sorted" which does exactly what I was looking for.
for k in sorted(somedictionary.keys()):
dosomething()
It shows up in Python 2.5 dictionary 2 key sort
Actually, .keys() is not necessary:
for k in sorted(somedictionary):
doSomething(k)
or
[doSomethinc(k) for k in sorted(somedict)]