user5137286
user5137286

Reputation:

How to simultaneously assign value to dictionary?

When I have a existing dictionary, I want to simultaneously assign value to it.

Example:

It's a sample about dictionary.

people_list = {
    "Tom": None,
    "David": None,
    "Traivs": None,
}

I want each of key:value pairs has same value.

This is my wanted result.

people_list = {
    "Tom": "hello",
    "David": "hello",
    "Traivs": "hello",
}

Except loop-statement, what do I solve it?

Upvotes: 1

Views: 154

Answers (5)

mhawke
mhawke

Reputation: 87134

There is no magical way to simultaneously set all immutable values in a dictionary in the manner that you request without some form of iteration occurring at some level.

Possibly the closest is to use dict.fromkeys():

people_list = dict.fromkeys(people_list, 'hello')

Although, of course, iteration is still occurring within fromkeys().

If you are happy with a level of indirection, it is possible to have a dictionary with mutable values, e.g. a list, and to update all of those at once:

>>> v = [None]
>>> d = {k:v for k in ['Tom', 'David', 'Traivis']}
>>> print d
{'David': [None], 'Traivis': [None], 'Tom': [None]}
>>> v[0] = 'hello'
>>> print d
{'David': ['hello'], 'Traivis': ['hello'], 'Tom': ['hello']}

Here there is no loop, but the downside is that the value must be extracted:

>>> d['Tom']
['hello']
>>> d['Tom'][0]
'hello'

Upvotes: 1

Sait
Sait

Reputation: 19855

In [3]: {key: 'hello' for key in people_list}
Out[3]: {'David': 'hello', 'Tom': 'hello', 'Traivs': 'hello'}

Time comparison with @Paul's solution:

In [12]: d = dict(zip(range(1, 10000), range(10000,1)))

In [13]: %timeit d2 = {key: 'hello' for key in d}
1000000 loops, best of 3: 240 ns per loop

In [14]: %timeit d.update(dict.fromkeys(d.keys(),"hello"))
1000000 loops, best of 3: 844 ns per loop

Upvotes: 3

Ozgur Vatansever
Ozgur Vatansever

Reputation: 52213

You can also use defaultdict if you want a dictionary with same values:

>>> from collections import defaultdict
>>> people_list = defaultdict(lambda: "hello")
>>> print people_list["Tom"]
'hello'
>>> print people_list["Davis"]
'hello'
>>> print people_list["Travis"]
'hello'

Key/value pairs are created on-demand.

Upvotes: 1

nivix zixer
nivix zixer

Reputation: 1651

It's still technically a loop, but you could use an iterator:

new_value = None
dict(map(lambda (k,v): (k, new_value), people_list.iteritems()))

Upvotes: 2

Paul Cornelius
Paul Cornelius

Reputation: 11009

One line:

people_list.update(dict.fromkeys(people_list.keys(),"hello"))

Upvotes: 3

Related Questions