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.
Related
This question already has answers here:
How do I clone a list so that it doesn't change unexpectedly after assignment?
(24 answers)
Closed 1 year ago.
This is the worst blocker that I have ever had attempting to learn Python. I spent about 10 hours on this one and could really use help.
I want to have dictionaries hold lists in python and then access and change a specific value in those lists. When I do this the way that seems logical to me and access a key then list value, it actually replaces other key's list values.
If I just assign 100 to the key XList it prints 100 for both XList and YList. Why does assigning to one key effect the other???
And if I uncomment the assignment to YList it prints 254 for both. Why can't I assign itemized values to keys and lists like this? How can I assign specific values to lists within dictionaries and access the main lists via keys?? Why does what seems like changing just one keys list value change both key's lists???
testDictKeys= ['XList', 'YList', 'ZList']
testDict = dict.fromkeys(['XList', 'YList', 'ZList'])
noneFillerList = [None] * 30
#Now fill all the columns and row of the dictionary with zeros
for x in range(0,2):
testDict[testDictKeys[x]] = noneFillerList
for x in range(0, 29):
testDict['XList'][x]=100
#testDict['YList'][x]=254
print (testDict['XList'][0])
print (testDict['YList'][0])
Any help is appreciated.
The problem is that you only create one list and assign every dictionary to contain it. To fix the problem, be sure to create a new list to add to each dictionary.
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()))
This question already has answers here:
Convert a python dict to a string and back
(12 answers)
Closed 3 years ago.
I have a predefined dictionary, and I want to be able to search the keys and values of the dictionary for a target string.
For example, if this is my dictionary:
my_dict = {u'GroupName': 'yeahyeahyeah', u'GroupId': 'sg-123456'}
I want to be check whether 'yeahyeahyeah' or 'GroupId' are in the keys or values of the dictionary. I think I want to convert the entire dictionary into a string, so that I can just do a substring search, but am open to other ideas.
EDIT: taking advice from comments
Here's how to create a list from the key value pairs in your dictionary.
my_dict = [{u'GroupName': 'yeahyeahyeah', u'GroupId': 'sg-123456'}]
my_list = list(my_dict[0].keys()) + list(my_dict[0].values())
This returns:
['GroupName', 'yeahyeahyeah', 'GroupId', 'sg-123456']
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:
Dictionary creation with fromkeys and mutable objects. A surprise [duplicate]
(3 answers)
Closed 8 years ago.
I have a dictionary indexed by 201 integer keys (0..200). the value for each of these keys is a list. generated with the code below:
dictionary=dict.fromkeys(range201,[])
i am getting this strange behaviour when i try to append items to the list belonging to one specific index, if i do this:
dictionary[1].append("foo")
i would expect this:
>>dictionary
{0:[], 1:["foo"],2:[],...}
but instead i end up with this:
>>dictionary
{0:["foo"], 1:["foo"],2:["foo"],...}
to clarify a bit the context in which the operation is performed, i am enumerating a list of values that can be None or float, i want to skip the None and append the float to the list corresponding to the enumerate index:
for i, value in enumerate(valuesList):
if value is None:
continue
dictionary[i].append(value)
this is behaviour is independent of which integer index i use, and i end up with the same values at all indices. I could use a list of lists and achieve the same result i think. but i wanted to understand this behaviour.
This is the normal behavior. All the entry of your dictionary where initialized with a reference to the same list. So when appending an element using one key, as all the key are pointing the same list, the modification is applied to all the entries of the dic.
Try this instead :
dictionary={}
for i in range(201):
#the loop make the list.__init__() (i.e. the []) being called 200 times
dictionary[i] = []
dictionary[1].append("foo")
print dictionary