Reputation: 608
I have two lists:
list1 = ['r', '8', 'w', 'm', 'f', 'c', 'd',...]
list2 = ['AA', 'AB', 'AC', 'AD', 'AE', 'AF',...]
I wish to put both of them into a dictionary such that:
{'r':'AA', '8':'AB', 'w':'AC', 'm':'AD',...}
I have tried using:
dictionary = dict(zip(list1, list2))
However, I believe this function does some sort of strange ordering as I get the following output if I print "dictionary":
{'1': 'BE', '0': 'EB', '3': 'CE', '2': 'FE', '5': 'DB',...}
Why is this, and how would the desired output be produced?
Upvotes: 0
Views: 62
Reputation: 1
This might give you a proper Dictionary without any brackets, mentioned in the comment above, Simple looping would be sufficient
list1 = ['a','b','c','d']
list2 = ['1','2','3','4']
dictionary = {}
def MakeIntoDictionary(List1, List2, Dictionary):
minlength = min(len(List1), len(List2))
for x in range(0, minlength):
Dictionary[List1[x]] = List2[x]
MakeIntoDictionary(list2, list1, dictionary)
Upvotes: 0
Reputation: 908
Dictionaries behave as unordered lists, so it has nosense trying to order them as [explained in python docs](https://docs.python.org/2/tutorial/datastructures.html#dictionaries. However, using a loops to assign values)
However, you can append them to an empty dictionary using loops, like this:
myDict = {}
list1 = ['r', '8', 'w', 'm', 'f', 'c', 'd',...]
list2 = ['AA', 'AB', 'AC', 'AD', 'AE', 'AF',...]
#To prevent different length issues,
# set max and min length of both lists
max_len = max(len(list1), len(list2))
min_len = min(len(list1), len(list2))
list1IsBigger = len(list1) > len(list2)
# We loop using the min length
for n in xrange(0, min_len):
myDict[list1[n]] = list2[n]
#From here, do whatever you like with
# remaining items from longer list
if len(list1) != len(list2):
for n in xrange(min_len, max_len):
if list1IsBigger:
#Do whatever with list1 here
else:
#Do whatever with list2 here
Upvotes: 0
Reputation: 39
Python dictionary, how to keep keys/values in same order as declared?
Dictionary is not meant to be ordered. Use orderedDict for this purpose
Upvotes: 0
Reputation: 363123
Dictionaries are an unordered data structure. The items from your pair of lists will still be paired correctly, but the ordering will be lost.
If you required the ordering of the lists to be preserved in the dict, you can use an OrderedDict
instead. Note that OrderedDict
is not as performant as a regular dict
, so don't use them unless you actually need the ordering.
>>> from collections import OrderedDict
>>> list1 = ['r', '8', 'w', 'm', 'f', 'c', 'd']
>>> list2 = ['AA', 'AB', 'AC', 'AD', 'AE', 'AF']
>>> OrderedDict(zip(list1, list2))
OrderedDict([('r', 'AA'),
('8', 'AB'),
('w', 'AC'),
('m', 'AD'),
('f', 'AE'),
('c', 'AF')])
Upvotes: 6