Reputation: 320
I have with me two values like p and q where p is an integer and q is a string.
I need a data structure to store such values as (p,q)
in python and the structure should be like I have to sort it in the future and print out first n elements.
I have tried dictionaries
but after sorting I couldn't display the first n elements as the dictionary
is an unordered list.
I won't be changing the values in the future.
Upvotes: 0
Views: 352
Reputation: 96
You can use a 2d array. I am assuming the p and q are list with the same length. have a look to the code below.
p = [1,5,7,3,5,7,45,23]
q = ['one', 'five', 'seven', 'three', 'five', 'seven', 'forty five', 'twenty three']
array = [[ 0 for x in range(2)] for y in range(len(p))]
for index, val in enumerate(p):
array[index][0] = val
array[index][1] = q[index]
print "first five to display:"
for i in range(5):
print str(array[i][0]) + " - " + array[i][1]
print
print "sorted array by the integer"
for val in sorted(array):
print str(val[0]) + " - " + val[1]
Upvotes: 1
Reputation: 79
OrderedDict objects Ordered dictionaries are just like regular dictionaries but they remember the order that items were inserted. When iterating over an ordered dictionary, the items are returned in the order their keys were first added.
Upvotes: 1