Using a list comprehension:
Copy>>> [dct[k] for k in lst]
[5, 3, 3, 3, 3]
Using map:
Copy>>> [*map(dct.get, lst)]
[5, 3, 3, 3, 3]
Answer from wim on Stack OverflowUsing a list comprehension:
Copy>>> [dct[k] for k in lst]
[5, 3, 3, 3, 3]
Using map:
Copy>>> [*map(dct.get, lst)]
[5, 3, 3, 3, 3]
You can use a list comprehension for this:
Copylstval = [ dct.get(k, your_fav_default) for k in lst ]
I personally propose using list comprehensions over built-in map because it looks familiar to all Python programmers, is easier to parse and extend in case a custom default value is required.
Videos
In Python 3 you can use this dictionary comprehension syntax:
def foo(somelist):
return {x[0]:x for x in somelist}
I don't think a standard function exists that does exactly that, but it's very easy to construct one using the dict builtin and a comprehension:
def somefunction(keyFunction, values):
return dict((keyFunction(v), v) for v in values)
print somefunction(lambda a: a[0], ["hello", "world"])
Output:
{'h': 'hello', 'w': 'world'}
But coming up with a good name for this function is more difficult than implementing it. I'll leave that as an exercise for the reader.
So I have a list of characters. And let's say I need to get at each of the characters class types. Using map() in python 3, how exactly would one go about this? Here's the list of characters. I've tried going at this a few ways, but they have all failed. The real issue is that I'm not sure how to get at the nested dictionary.
chars = [{'Character1': {'age': 19, 'name': 'Balthazar',
'class': 'Wizard'}}, {'Character2': {'age': 24,
'name': 'Thadeus', 'class': 'Warrior'}}]
classes = list(map(lambda x: x.update({"classes":
list(map(lambda y: # need to get at each 'class' key
here to output to the list of classes), collection)}),
chars))EDIT: This is something I'm working on at work. I'm a Jr. Dev, and these made up dictionaries hold no value to what I'm actually working on whatsoever. I just need to understand how this works and am not coming up with much in my searching.
I am trying to add a list, or a tuple of lists, as the value to a key inside a dictionary. I'm starting with a dictionary that has empty lists as values, and then adding to the value of each key inside a loop like this:
dict = {'key1': [], 'key2': [], 'key3': []}
list = ['a', 'b']
for key,value in dict.items():
# dict[key].append(list)
value.append(list)
print(dict)What is the difference between dict[key].append(list) and value.append(list)? They both produce the same dictionary when the other is commented out.
Further, how would I add a second list to one of these values as a tuple? Something like adding the list ['c', 'd'] to key2, like this:
{'key1': [['a', 'b']], 'key2': [['a', 'b'], ['c', 'd']], 'key3': [['a', 'b']]}Thanks for any replies!