user2847624
user2847624

Reputation: 9

How to assign key from list for dictionary?

I have to write a method, using a dictionary, which takes a list a and returns a list containing the elements of a that occur once and elements should appear in the same order as their first occurrence in a. Do I think in right direction? This is my code:

def only_once(a):
    d = {}
    for i in a:
        d['value'] = i
    m = range(len(a))
    for num in m:
        d['key'] = num
    return d.value  

How to take elements from list a and make values?

Upvotes: 0

Views: 100

Answers (3)

EmEs
EmEs

Reputation: 179

This is my solution using dict comprehension and sorting dict keys by corresponding values:

def only_once(a):
   # create the dictionary using dict comprehension;
   # add to the dictionary only if the number of occurences
   # equals one
   d = {x:a.index(x) for x in a if a.count(x) == 1}

   # retrieve the dictionary keys as list and sort them by the value
   # of their assigned dictionary values
   return sorted(d.keys(), key = d.get)

but I agree that dict is not the most fortunate choice of datastructure for solving this problem.

Upvotes: 0

kojiro
kojiro

Reputation: 77137

Here's a naïve solution. It pretty much uses a dict as a set, which is silly, because python has sets. But hey.

def only_once(a):
  d = {}
  for i in a:
    d.setdefault(i,0)
    d[i] += 1
  return [i for i in a if d[i] == 1]

Upvotes: 0

Rohit Jain
Rohit Jain

Reputation: 213261

itertools has a recipe for this task:

def unique_everseen(iterable, key=None):
    "List unique elements, preserving order. Remember all elements ever seen."
    # unique_everseen('AAAABBBCCDAABBB') --> A B C D
    # unique_everseen('ABBCcAD', str.lower) --> A B C D
    seen = set()
    seen_add = seen.add
    if key is None:
        for element in ifilterfalse(seen.__contains__, iterable):
            seen_add(element)
            yield element
    else:
        for element in iterable:
            k = key(element)
            if k not in seen:
                seen_add(k)
                yield element

BTW, since you want the order to be the same, a dictionary won't help here. A dict doesn't maintain any order.

Upvotes: 2

Related Questions