dictionary-comprehension

List of tuples to dictionary with duplicates keys via list comprehension?

荒凉一梦 提交于 2020-06-22 19:30:13
问题 I have a list of tuples with duplicates and I've converted them to a dictionary using this code I found here: https://stackoverflow.com/a/61201134/2415706 mylist = [(a,1),(a,2),(b,3)] result = {} for i in mylist: result.setdefault(i[0],[]).append(i[1]) print(result) >>> result = {a:[1,2], b:[3]} I recall learning that most for loops can be re-written as comprehensions so I wanted to practice but I've failed for the past hour to make one work. I read this: https://stackoverflow.com/a/56011919

What's wrong with this dictionary comprehension code?

时光总嘲笑我的痴心妄想 提交于 2020-05-31 04:55:05
问题 I have a python dictionary which is some kind of a glossary. glossary_dict = {'AA': 'AA_meaning', 'BB': 'BB_meaning', 'CC': 'CC_meaning', } Here is the original dictionary. original = [{'AA': '299021.000000'}, {'BB': '299021.000000'}, {'CC': '131993.000000'}, ] I want to replace the keys of original dictionary with the corresponding value of glossary_dict . The final result will look like this; explained = {'AA_meaning': '299021.000000', 'BB_meaning': '299021.000000', 'CC_meaning': '131993

How to reuse an expression in a comprehension expression?

谁说胖子不能爱 提交于 2020-04-30 06:32:26
问题 Imagine a theoretical snippet: # just for this example: `bad_structure` contains a list of dicts with different keys # for the same semantic bad_structure = [{'path': '/dir/one'}, {'subdir': '/dir/two'}] # i want to turn this into # { '/dir/one': some_func('/dir/one'), # '/dir/two': some_func('/dir/two')} result = {} for e in bad_structure: # calculate a value which we will need more than once (here the key) p = next(k for k in ('path', 'subdir') if k in e) result[p] = some_func(p) I want to

Turning a list of dictionaries into a list of lists

a 夏天 提交于 2020-01-30 06:30:08
问题 I know this is possible with list comprehension but I can't seem to figure it out. Currently I have a list of dictionaries like so: [ {'field1': 'a', 'field2': 'b'}, {'field1': 'c', 'field2': 'd'}, {'field1': 'e', 'field2': 'f'} ] I'm trying to turn this into: list = [ ['b', 'a'], ['d', 'c'], ['f', 'e'], ] 回答1: You can try: [[x['field2'], x['field1']] for x in l] where l is your input list. The result for your data would be: [['b', 'a'], ['d', 'c'], ['f', 'e']] This way you ensure that the

Find count of characters within the string in Python

感情迁移 提交于 2020-01-30 04:34:07
问题 I am trying to create a dictionary of word and number of times it is repeating in string. Say suppose if string is like below str1 = "aabbaba" I want to create a dictionary like this word_count = {'a':4,'b':3} I am trying to use dictionary comprehension to do this. I did dic = {x:dic[x]+1 if x in dic.keys() else x:1 for x in str} This ends up giving an error saying File "<stdin>", line 1 dic = {x:dic[x]+1 if x in dic.keys() else x:1 for x in str} ^ SyntaxError: invalid syntax Can anybody tell

Python Dictionary comprehension to copy some pairs to a new dictionary

為{幸葍}努か 提交于 2020-01-06 14:57:15
问题 While playing around with input validation, specifically checking whether the supplied data have all the required attributes specified, and discarding attributes that I don't want, I did something like this: >>> input = {'v1': 'val1', 'a2':'val2', 'a3':'val3'} >>> print input {'v1': 'val1', 'a3': 'val3', 'a2': 'val2'} >>> goodkeys = ['a2', 'a3'] >>> print goodkeys ['a2', 'a3'] >>> output = {} >>> for a in goodkeys: ... output[a] = input[a] ... >>> >>> print output {'a3': 'val3', 'a2': 'val2'}

Python Dictionary comprehension to copy some pairs to a new dictionary

可紊 提交于 2020-01-06 14:57:15
问题 While playing around with input validation, specifically checking whether the supplied data have all the required attributes specified, and discarding attributes that I don't want, I did something like this: >>> input = {'v1': 'val1', 'a2':'val2', 'a3':'val3'} >>> print input {'v1': 'val1', 'a3': 'val3', 'a2': 'val2'} >>> goodkeys = ['a2', 'a3'] >>> print goodkeys ['a2', 'a3'] >>> output = {} >>> for a in goodkeys: ... output[a] = input[a] ... >>> >>> print output {'a3': 'val3', 'a2': 'val2'}

Ternary expression in dictionary comprehension

蓝咒 提交于 2019-12-30 07:00:14
问题 I'm trying to invert a dictionary. In the case of many keys having the same value, the new key (old value) should associate with a set of the new values (old keys). I solved the problem, but I'm trying to refactor using dictionary comprehension, and some helper methods. def has_unique_value(k): return d.values().count(d[k]) == 1 def keys_with_same_value_as_key(k): return set([key for key in d.keys() if d[key] == d[k]]) print( {d[k]:k if has_unique_value(k) else d[k]:keys_with_same_value_as

Create dictionary comprehension from list with condition syntax

…衆ロ難τιáo~ 提交于 2019-12-25 18:14:21
问题 I'd like to create a dictionary using dictionary comprehension syntax. Note that list l contains tuples of strings and tuples with 1st element always a time stamp. This works: d = {} for entry in l: if entry[0] not in d: d[entry[0]] = [] d[entry[0]].append(entry) This doesn't work: d = {k[0].append(k) for k in l if k[0] in d else k[0]:k for k in l} File "<stdin>", line 1 d = {k[0].append(k) for k in l if k[0] in d else k[0]:k for k in l} ^ SyntaxError: invalid syntax 回答1: You can't use a

Update value of dict2 from dict1 but in a specific place in dict2

为君一笑 提交于 2019-12-25 02:14:01
问题 Having 2 dictionaries I want to insert the values of dict1 into dict2 but in a specific place in dict2 I asked a similar question here which was solved in this way: d = {k: v.replace(k, k+' '+dict1[k]) for k, v in dict2.items()} But I'm interested in how we would solve this similar problem: Dict1 { 'apple': 'hard tasty', 'orange': 'soft tasty', 'banana': 'soft very-tasty' } Dict2 { 'apple': '<div class="a"></div>', 'orange': '<div class="o"></div>', 'banana': '<div class="b a"></div>' }