Python Dictionary Comprehension
There are dictionary comprehensions in Python 2.7+, but they don't work quite the way you're trying. Like a list comprehension, they create a new dictionary; you can't use them to add keys to an existing dictionary. Also, you have to specify the keys and values, although of course you can specify a dummy value if you like.
>>> d = {n: n**2 for n in range(5)}
>>> print d
{0: 0, 1: 1, 2: 4, 3: 9, 4: 16}
If you want to set them all to True:
>>> d = {n: True for n in range(5)}
>>> print d
{0: True, 1: True, 2: True, 3: True, 4: True}
What you seem to be asking for is a way to set multiple keys at once on an existing dictionary. There's no direct shortcut for that. You can either loop like you already showed, or you could use a dictionary comprehension to create a new dict with the new values, and then do oldDict.update(newDict)
to merge the new values into the old dict.
Create a dictionary with comprehension
Use a dict comprehension (Python 2.7 and later):
{key: value for (key, value) in iterable}
Alternatively for simpler cases or earlier version of Python, use the dict
constructor, e.g.:
pairs = [('a', 1), ('b', 2)]
dict(pairs) #=> {'a': 1, 'b': 2}
dict([(k, v+1) for k, v in pairs]) #=> {'a': 2, 'b': 3}
Given separate arrays of keys and values, use the dict
constructor with zip
:
keys = ['a', 'b']
values = [1, 2]
dict(zip(keys, values)) #=> {'a': 1, 'b': 2}
2) "zip'ped" from two separate iterables of keys/vals
dict(zip(list_of_keys, list_of_values))
Dictionary Comprehension within a List Comprehension
It is hard to read/understand, but this works:
show_mac = [{key:value.replace('TenGigabitEthernet', 'Te').replace('GigabitEthernet', 'Gi').replace('Port-channel', 'Po') for (key, value) in line.items()}) for line in show_mac]
print(show_mac)
how to do dict comprehension for multiple for and if loops in python?
You should put the filter as an if
clause in the comprehension. Also, use the dict.get
method to default the value to None
when a key is not found in the dict:
out = {
each_val['value']: each_val.get('frequency')
for each_val in values["data"]['values']
if each_val['value'].strip() != ''
}
List/Dict comprehension in Python to update a dictionary with keys and values from a string
Find unique keys with set and then count. Note the set
doesn't not keep (keys) insertion order!
stringOne = 'abcddd'
dictResult = {char: stringOne.count(char) for char in set(stringOne)}
print(dictResult)
Alternative way to use setdefault() using dictionary comprehension?
Use the loop because it's very readable and efficient. Not all code has to be a one-liner.
Having said that, it's possible. It abuses syntax, extremely unreadable, inefficient, and generally just plain bad code (don't do it!)
out = {k: next(gg for gg in [{}] if all(gg.setdefault(a, b) for a,b in v)) for k, v in next(g for g in [{}] if not any(g.setdefault(key, []).append(v) for key, *v in list1)).items()}
Output:
{1: {2: 6, 3: 7}, 2: {5: 8, 8: 9}}
Related Topics
How to Change the Datetime Format in Pandas
How to Improve Performance of This Code
Best Way to Return Multiple Values from a Function
Create a Pandas Dataframe by Appending One Row At a Time
How to Explicitly Free Memory in Python
Urllib and "Ssl: Certificate_Verify_Failed" Error
"Unicode Error "Unicodeescape" Codec Can't Decode Bytes... Cannot Open Text Files in Python 3
What Is the Eafp Principle in Python
"Large Data" Workflows Using Pandas
What's the Difference Between Lists and Tuples
How to Pad a String With Zeroes
How to Have One Colorbar For All Subplots
Iterate a List as Pair (Current, Next) in Python
How to Pass a Variable Between Flask Pages
Import a Module from a Relative Path
How to Expand the Output Display to See More Columns of a Pandas Dataframe