Vivek Sable
Vivek Sable

Reputation: 10213

Create dictionary where keys from the list and value is common

There is any better ways to create dictionary which keys are from the list and value is common?

Input: Document UID list and Project Name.

Output: Document UID and Project Name Dictionary Dictionary.

My Current Code:

>>> doc_uid = [u'AAAB3086', u'AAAB3085']
>>> project_name = "Custom Project One"
>>> doc_project_map = {}
>>> for ii in doc_uid:
...     doc_project_map[ii] = project_name
... 
>>> doc_project_map
{u'AAAB3086': 'Custom Project One', u'AAAB3085': 'Custom Project One'}
>>> 

Why I am doing this because in next process I have all Document UID and I have to find out its Project Name.

There are many Projects and each project contains many Document.

Actaul Algo is:

  1. Get All Projeect objects.
  2. Iterrate each Project OBJ by for loop.
  3. Get all documents of Project OBJ
  4. Iterate each document and add key as document UID and vakue as Project Name.

like:

  doc_project_map = {}
  for project_onj in project_objes:
      project_name = getProjectName(project_obj)
      docuents_uids = getProjectDcoumentUID(project_obj)
      for docuents_uid in docuents_uids:
          doc_project_map[docuents_uid] =  project_name

Upvotes: 1

Views: 98

Answers (3)

Padraic Cunningham
Padraic Cunningham

Reputation: 180391

from itertools import repeat, izip

d = dict(izip(doc_uid,repeat(project_name)))

Or use fromkeys as your value is immutable:

d = dict.fromkeys(doc_uid,project_name)

fromkeys is the most efficient using python2:

In [28]: doc_uid = range(100000)

In [29]: timeit dict(izip(doc_uid,repeat(project_name)))
100 loops, best of 3: 6.16 ms per loop

In [30]: timeit dict.fromkeys(doc_uid,project_name)
100 loops, best of 3: 5.16 ms per loop

In [31]: timeit dict(izip(doc_uid,len(doc_uid)*[project_name]))
100 loops, best of 3: 7.19 ms per loop

In [32]: timeit {k:project_name for k in doc_uid}
100 loops, best of 3: 7.22 ms per loop

Same order using python 3:

In [7]: timeit dict(zip(doc_uid,len(doc_uid)*[project_name]))
100 loops, best of 3: 13.1 ms per loop

In [8]: timeit dict.fromkeys(doc_uid,project_name)
100 loops, best of 3: 10.3 ms per loop

In [9]: timeit dict(zip(doc_uid,repeat(project_name)))
100 loops, best of 3: 11.7 ms per loop

In [10]: timeit {k:project_name for k in doc_uid}
100 loops, best of 3: 13.3 ms per loop

Upvotes: 1

acushner
acushner

Reputation: 9946

i would use dict.fromkeys and dict.update. you give it a list of keys and a value and it creates a dict for you.

final_dict = {}
for project_onj in project_objes:
    try:
        final_dict.update(dict.fromkeys(getProjectDcoumentUID(project_obj), getProjectName(project_obj)))  # copied your presumed typo directly
    except:
        pass  # handle error here

Upvotes: 1

Overclover
Overclover

Reputation: 2182

dict(zip(doc_uid,len(doc_uid)*[project_name]))

Upvotes: 2

Related Questions