-6

i'm new to python I have Ordered dictionary

dictA = {f1 : ["s","r"], 
        f2 : ["p"], 
        f3 : ["w","t"]}

How do I form a list that should have only 1st elements from values present in dictionary dictA and followed by 2nd elements ... and so on, until it reached the list_size_limit = 5

Final list ["s","p","w","r","t"]

if the list_size_limit = 3

Final list = ["s","p","w"]

How do i form a list which has 1st elements of all values of dictionary to be present in list 1st, followed by 2nd elements...3rd elements

FryMan
  • 51
  • 2
  • 9
  • 3
    What have you tried, and what precisely is the problem with it? Note that you can't guarantee output order of values from a dictionary, it's not clear whether you need that. – jonrsharpe Mar 28 '16 at 07:56
  • There's an inherent problem with this question. Dictionaries are unordered on their keys, so `list` with `list_size_limit == 3` could be any permutation of `{"s", "p", "w"}`. [`OrderedDict`](https://docs.python.org/3/library/collections.html#collections.OrderedDict) can help with that at least. – Alyssa Haroldsen Mar 28 '16 at 08:00
  • i have Orderdict() dictA is ordered – FryMan Mar 28 '16 at 08:14
  • I need all the 1st elements of all values of dictionary to be present in list 1st, followed by 2nd elements...3rd elements – FryMan Mar 28 '16 at 08:17
  • 1
    "i have Orderdict() dictA is ordered" Please add this to the question. – Stop harming Monica Mar 28 '16 at 08:19

2 Answers2

2

Honestly not sure what to call this function. Naming things is hard.

def getFirstOfDictList(d, limit=None):
    if limit is None:
        limit = float('inf')
    done = 0
    iters = [iter(i) for i in d.values()]
    items = []
    while iters:
        toRemove = []
        for iterator in iters:
            if done >= limit:
                return items
            try:
                items.append(next(iterator))
                done += 1
            except StopIteration:
                toRemove.append(iterator)
        for finishedIterator in toRemove:
            iters.remove(finishedIterator)
    return items
Alyssa Haroldsen
  • 3,652
  • 1
  • 20
  • 35
0
dictA = {"f1" : ["m"],
        "f2" : ["p","y","o","a","s","d","f","g"],
        "f3" : ["w","t"],
         "f5" : ["z","x"],
         "f6" : ["c","v"]}

result = []
limit_size = 3
values_list = []
for values in dictA.itervalues():
    values_list.append(len(values))

for i in range(0,max(values_list)):
    keys = list(dictA.keys())
    count = 0
    while count < len(keys):
        try:
            result.append(dictA[keys[count]][i])
        except IndexError:
            dictA.pop(keys[count])
        count = count + 1
print "final ",result[0:limit_size]
FryMan
  • 51
  • 2
  • 9