different list values for dictionary keys

  • Last Update :
  • Techknowledgy :

Last Updated : 17 May, 2020

 
Output:

[1, 2, 3, 4, 5]: 1
   (1, 2, 3, 4, 5): 1

Suggestion : 2

A list comprehension seems to be a good way to do this:

>>> [mydict[x]
   for x in mykeys
]
[3, 1]

Alternatively, using operator.itemgetter can return a tuple:

from operator
import itemgetter
myvalues = itemgetter( * mykeys)(mydict)
# use `list(...)`
if list is required

A little speed comparison:

Python 2.7 .11 | Anaconda 2.4 .1(64 - bit) | (
   default, Dec 7 2015, 14: 10: 42)[MSC v .1500 64 bit(AMD64)] on win32
In[1]: l = [0, 1, 2, 3, 2, 3, 1, 2, 0]
In[2]: m = {
   0: 10,
   1: 11,
   2: 12,
   3: 13
}
In[3]: % timeit[m[_]
   for _ in l] # list comprehension
1000000 loops, best of 3: 762 ns per loop
In[4]: % timeit map(lambda _: m[_], l) # using 'map'
1000000 loops, best of 3: 1.66 µs per loop
In[5]: % timeit list(m[_]
   for _ in l) # a generator expression passed to a list constructor.
1000000 loops, best of 3: 1.65 µs per loop
In[6]: % timeit map(m.__getitem__, l)
The slowest run took 4.01 times longer than the fastest.This could mean that an intermediate result is being cached
1000000 loops, best of 3: 853 ns per loop
In[7]: % timeit map(m.get, l)
1000000 loops, best of 3: 908 ns per loop
In[33]: from operator
import itemgetter
In[34]: % timeit list(itemgetter( * l)(m))
The slowest run took 9.26 times longer than the fastest.This could mean that an intermediate result is being cached
1000000 loops, best of 3: 739 ns per loop

For large random lists and maps I had a bit different results:

Python 2.7 .11 | Anaconda 2.4 .1(64 - bit) | (
   default, Dec 7 2015, 14: 10: 42)[MSC v .1500 64 bit(AMD64)] on win32
In[2]: import numpy.random as nprnd
l = nprnd.randint(1000, size = 10000)
m = dict([(_, nprnd.rand()) for _ in range(1000)])
from operator
import itemgetter
import operator
f = operator.itemgetter( * l)

   %
   timeit f(m)
1000 loops, best of 3: 1.14 ms per loop

   %
   timeit list(itemgetter( * l)(m))
1000 loops, best of 3: 1.68 ms per loop

   %
   timeit[m[_]
      for _ in l] # list comprehension
100 loops, best of 3: 2 ms per loop

   %
   timeit map(m.__getitem__, l)
100 loops, best of 3: 2.05 ms per loop

   %
   timeit list(m[_]
      for _ in l) # a generator expression passed to a list constructor.
100 loops, best of 3: 2.19 ms per loop

   %
   timeit map(m.get, l)
100 loops, best of 3: 2.53 ms per loop

   %
   timeit map(lambda _: m[_], l)
100 loops, best of 3: 2.9 ms per loop

Update for Python 3.6.4

import numpy.random as nprnd
l = nprnd.randint(1000, size = 10000)
m = dict([(_, nprnd.rand()) for _ in range(1000)])
from operator
import itemgetter
import operator
f = operator.itemgetter( * l)

   %
   timeit f(m)
1.66 ms± 74.2 µs per loop(mean± std.dev.of 7 runs, 1000 loops each)

   %
   timeit list(itemgetter( * l)(m))
2.1 ms± 93.2 µs per loop(mean± std.dev.of 7 runs, 100 loops each)

   %
   timeit[m[_]
      for _ in l] # list comprehension
2.58 ms± 88.8 µs per loop(mean± std.dev.of 7 runs, 100 loops each)

   %
   timeit list(map(m.__getitem__, l))
2.36 ms± 60.7 µs per loop(mean± std.dev.of 7 runs, 100 loops each)

   %
   timeit list(m[_]
      for _ in l) # a generator expression passed to a list constructor.
2.98 ms± 142 µs per loop(mean± std.dev.of 7 runs, 100 loops each)

   %
   timeit list(map(m.get, l))
2.7 ms± 284 µs per loop(mean± std.dev.of 7 runs, 100 loops each)

   %
   timeit list(map(lambda _: m[_], l) 3.14 ms± 62.6 µs per loop(mean± std.dev.of 7 runs, 100 loops each)

Raising KeyError when key is not found:

result = [mapping[k]
   for k in iterable
]

Default values for missing keys.

result = [mapping.get(k, default_value) for k in iterable]

Skipping missing keys.

result = [mapping[k]
   for k in iterable
   if k in mapping
]

Try This:

mydict = {
   'one': 1,
   'two': 2,
   'three': 3
}
mykeys = ['three', 'one', 'ten']
newList = [mydict[k]
   for k in mykeys
   if k in mydict
]
print newList
   [3, 1]

Try this:

mydict = {
   'one': 1,
   'two': 2,
   'three': 3
}
mykeys = ['three', 'one'] #
if there are many keys, use a set

   [mydict[k]
      for k in mykeys] => [3, 1]

Suggestion : 3

The media shown in this article are not owned by Analytics Vidhya and are used at the Author’s discretion.,Dictionaries are mutable data types in nature meaning they can be updated after they are created. Syntactically they are written in a key, value pair format inside curly braces.,Python is a high-level general-purpose programming language. Python is one of the most popular and widely used programming languages in the world Python is used for data analytics, machine learning, and even design. Python is used in a wide range of domains owing to its simple yet powerful nature. In this article, we will be discussing lists & dictionaries datatypes.,We will use the same dictionary object dict_salesinfo. Using the keys function first save all the keys in a dict_key variable

Output

Ahmedabad
30

We also have a negative index number as shown below

print(city_list[-1])

Index range represents the portion of the list that you want to extract as shown in the below example

print(city_list[2: 5])

The addition of two lists can be performed using the + operator. The + operator concatenates both the lists

num_city_list = num_list + city_list
print(num_city_list)

The * operator is used to extend the list by copying the same values

new_citylist = city_list * 2
print(new_citylist)

Output

[
   [10, 20, 30],
   ['a', 'b', 'c']
]
sales_id = 'SID2'
if sales_id in dict_salesid:
   name = dict_salesid[sales_id]
print('Sales ID is {}, Sales name is {}'.format(sales_id, name))
else:
   print('Sales ID {} not found'.format(sales_id))

Suggestion : 4

DictionaryKeys (last edited 2022-01-21 13:47:38 by eriky)

   1 # retrieve the value
   for a particular key
   2 value = d[key]
   1 def lookup(d, key):
      2 ''
   'dictionary lookup is done in three steps:
   3 1. A hash value of the key is computed using a hash
   function.
   4
   5 2. The hash value addresses a location in d.data which is
   6 supposed to be an array of "buckets"
   or "collision lists"
   7 which contain the(key, value) pairs.
   8
   9 3. The collision list addressed by the hash value is searched
   10 sequentially until a pair is found with pair[0] == key.The
   11
   return value of the lookup is then pair[1].
   12 ''
   '
   13 h = hash(key) # step 1
   14 cl = d.data[h] # step 2
   15
   for pair in cl: # step 3
   16
   if key == pair[0]:
      17
   return pair[1]
   18
   else:
      19 raise KeyError, "Key %s not found." % key
1._
   1 # retrieve the value
   for a particular key
   2 value = d[key]
2._
   1 def lookup(d, key):
      2 ''
   'dictionary lookup is done in three steps:
   3 1. A hash value of the key is computed using a hash
   function.
   4
   5 2. The hash value addresses a location in d.data which is
   6 supposed to be an array of "buckets"
   or "collision lists"
   7 which contain the(key, value) pairs.
   8
   9 3. The collision list addressed by the hash value is searched
   10 sequentially until a pair is found with pair[0] == key.The
   11
   return value of the lookup is then pair[1].
   12 ''
   '
   13 h = hash(key) # step 1
   14 cl = d.data[h] # step 2
   15
   for pair in cl: # step 3
   16
   if key == pair[0]:
      17
   return pair[1]
   18
   else:
      19 raise KeyError, "Key %s not found." % key

For such a lookup algorithm to work correctly, the hash functions provided must guarantee that if two keys produce different hash values then the two key objects are not equivalent, that is,

for all i1, i2,
if hash(i1) != hash(i2), then i1 != i2

Note that this function meets the requirements of a hash function - every time two keys have different hash values, they represent different objects. (This is trivially true because no keys have different hash values - they all have the value 1.) But this is a bad hash function because it means that all (key, value) pairs will be placed in a single list, and so each lookup will require searching this entire list. Thus a (very) desirable property of a hash function is that if two keys produce the same hash values, then the key objects are equivalent, that is,

for all i1, i2,
if hash(i1) == hash(i2), then i1 == i2
6._
   1 >>> l = [1, 2]
   2 >>> d = {}
   3 >>> d[l] = 42
   4 >>> l.append(3)
   5 >>> d[l]
   6 Traceback (most recent call last):
   7   File "<interactive input>", line 1, in ?
   8 KeyError: [1, 2, 3]
   9 >>> d[[1, 2]]
  10 Traceback (most recent call last):
  11   File "<interactive input>", line 1, in ?
  12 KeyError: [1, 2]
   1 def hash(obj):
      2
   return 1
   1 >>> l = [1, 2]
   2 >>> d = {}
   3 >>> d[l] = 42
   4 >>> l.append(3)
   5 >>> d[l]
   6 Traceback (most recent call last):
   7   File "<interactive input>", line 1, in ?
   8 KeyError: [1, 2, 3]
   9 >>> d[[1, 2]]
  10 Traceback (most recent call last):
  11   File "<interactive input>", line 1, in ?
  12 KeyError: [1, 2]