标签: dictionary-comprehension

Scala展平嵌套地图

我有一个这样的嵌套地图:

Map(1 -> Map(2 -> 3.0, 4 -> 5.0), 6 -> Map(7 -> 8.0))
Run Code Online (Sandbox Code Playgroud)

我想以一种方式“展平”它,以便外部和内部地图的键配对,即对于上面的示例:

Seq((1,2),(1,4),(6,7))
Run Code Online (Sandbox Code Playgroud)

什么是优雅的方式来做到这一点?

scala scala-collections dictionary-comprehension

2
推荐指数
1
解决办法
2842
查看次数

字典理解中的嵌套循环

我有一个现有的字典列表如下:

FA = [{u'child': [{u'cdesc': u'Audit'},
                  {u'cdesc': u'Equity Research'},
                  {u'cdesc': u'Finance / Accounts / Tax'},
                  {u'cdesc': u'Investment Banking / M&A'}],
       u'pdesc': u'Finance / Accounts / Investment Banking',
       u'pid': 10007}]
Run Code Online (Sandbox Code Playgroud)

我想将它转换为这样的东西:

FA = {u'Audit':2,
     u'Equity Research':2,
     u'Finance / Accounts / Tax':2,
     u'Investment Banking / M&A':2,
     u'Finance / Accounts / Investment Banking':2}
Run Code Online (Sandbox Code Playgroud)

我可以使用嵌套循环轻松完成此操作,其代码如下所示.有没有办法使用词典理解来做到这一点?

a = dict()
for fa in FA:
    a.update({slugify(fa['pdesc']):2})


    for c in fa['child']: 
        a.update({slugify(c['cdesc']):2})
Run Code Online (Sandbox Code Playgroud)

python dictionary dictionary-comprehension

2
推荐指数
1
解决办法
1048
查看次数

将字典列表转换为列表列表

我知道这可以通过列表理解来实现,但我似乎无法弄明白.目前我有一个字典列表,如下所示:

 [ {'field1': 'a', 'field2': 'b'},
   {'field1': 'c', 'field2': 'd'},
   {'field1': 'e', 'field2': 'f'} ]
Run Code Online (Sandbox Code Playgroud)

我想把它变成:

list = [
    ['b', 'a'],
    ['d', 'c'],
    ['f', 'e'],
]
Run Code Online (Sandbox Code Playgroud)

python dictionary list-comprehension list dictionary-comprehension

2
推荐指数
1
解决办法
1231
查看次数

如何从Python中的嵌套列表创建字典?

我希望可能有一些使用理解来做到这一点,但是说我的数据看起来像这样:

data = [['a', 'b', 'c'], [1, 2, 3], [4, 5, 6]]
Run Code Online (Sandbox Code Playgroud)

我的最终目标是创建一个字典,其中第一个嵌套列表包含键,其余列表包含值:

{'a': [1, 4], 'b': [2, 5], 'c': [3, 6]}
Run Code Online (Sandbox Code Playgroud)

我已经尝试了类似这样的东西让我接近,但是你可以告诉我在字典值中附加列表时遇到问题,这段代码只是覆盖:

d = {data[0][c]: [] + [col] for r, row in enumerate(data) for c, col in enumerate(row)}
>>> d
{'c': [6], 'a': [4], 'b': [5]}
Run Code Online (Sandbox Code Playgroud)

python python-3.x dictionary-comprehension

2
推荐指数
1
解决办法
782
查看次数

嵌套字典理解:要解压缩的值太多

我尝试重写以下代码以使用字典理解,只是为了好玩:

import itertools

with open('foo.txt') as f:
    entities = f.read().splitlines()

parsed_entities = []
while entities:
    props = itertools.takewhile(lambda n: n != 'EOM', entities)
    entity = {p.split('=')[0]: p.split('=')[1] for p in props}
    entities = entities[len(entity)+2:]  # Delete and skip EOM & newline
    parsed_entities.append(entity)
Run Code Online (Sandbox Code Playgroud)

我想替换这一行:

entity = {p.split('=')[0]: p.split('=')[1] for p in props}
Run Code Online (Sandbox Code Playgroud)

具有更好看的字典理解,可能看起来像:

entity = {key: value for p in props for key, value in p.split('=')}
Run Code Online (Sandbox Code Playgroud)

当我尝试这样做时,我收到以下错误:

ValueError:解压缩的值太多(预期2)

我究竟做错了什么?使用ipdb.pm()我看到p是name=yam,这是很好的,但keyvalue没有定义.

python dictionary python-3.x dictionary-comprehension

2
推荐指数
1
解决办法
665
查看次数

使用字典理解转换Python字典

我有以下Python字典:

{
 "cat": 1,
 "dog": 1,
 "person": 2,
 "bear": 2,
 "bird": 3
}
Run Code Online (Sandbox Code Playgroud)

我想使用字典理解将其转换为以下字典:

{
 1 : ["cat", "dog"],
 2 : ["person", "bear"],
 3 : ["bird"]
}
Run Code Online (Sandbox Code Playgroud)

我怎么能在一个班轮里做这件事?

python dictionary dictionary-comprehension

2
推荐指数
1
解决办法
98
查看次数

将列表列表转换为字典

如何从Python列表列表创建字典,以便第一行是键,其余是该键下的列表?

x = [['A', 'B', 'C'],
 [100, 90, 80],
 [88, 99, 111],
 [45, 56, 67],
 [59, 61, 67],
 [73, 79, 83],
 [89, 97, 101]]
Run Code Online (Sandbox Code Playgroud)

目前我正在获得一个词典理解:

{i[0]: i[1:] for i in x}

{'A': ['B', 'C'],
 100: [90, 80],
 88: [99, 111],
 45: [56, 67],
 59: [61, 67],
 73: [79, 83],
 89: [97, 101]}
Run Code Online (Sandbox Code Playgroud)

期望的结果是:

{
"A": [100, 88, 45, 59, 73, 89],
"B": [90, 99, 56, 61, 79, 97],
"C": [80, 111, 67, 83, 101],
}
Run Code Online (Sandbox Code Playgroud)

如何以正确的方式切割词典理解?

python python-3.x dictionary-comprehension

2
推荐指数
1
解决办法
197
查看次数

Python 字典语法,有一个 for 条件

我有这本字典,

states = {
    'CT': 'Connecticut',
    'CA': 'California',
    'NY': 'New York',
    'NJ': 'New Jersey'
    }
Run Code Online (Sandbox Code Playgroud)

和代码在这里..

state2 = {state: abbrev for abbrev, state in states.items()}
Run Code Online (Sandbox Code Playgroud)

我试图了解这是什么以及如何abbrev for abbrev工作。我也不清楚究竟state:是什么。我得到了第二部分(states.items() 中的状态)。这个的输出给出

{'Connecticut': 'CT', 'California': 'CA', 'New York': 'NY', 'New Jersey': 'NJ'}
Run Code Online (Sandbox Code Playgroud)

但我不确定这是如何工作的.. 在此先感谢您。

python dictionary dictionary-comprehension iterable-unpacking

2
推荐指数
1
解决办法
49
查看次数

Python嵌套字典理解与if else

我正在尝试将以下内容转换为字典理解

my_dict = {'a': None, 'b': None, 'c': ['1', '2', '3']}
new_dict = {}
 for k, v in my_dict.items():
     if not v:
         new_dict[k] = None
     else:
         for item in v:
             new_dict[f'{k}{item}'] = None
Run Code Online (Sandbox Code Playgroud)

我正在尝试将我的 dict 翻译成

new_dict = {'a': None, 'b': None, 'c1': None, 'c2': None, 'c3': None}

Run Code Online (Sandbox Code Playgroud)

我对基本列表和字典理解相当满意,但在这个问题上挣扎,目前看起来像这样,但显然我对语法有点偏离:

{k: None if not v else f'{k}{item}': None for item in v for k, v in my_dict.items()}
Run Code Online (Sandbox Code Playgroud)

python dictionary-comprehension

2
推荐指数
1
解决办法
650
查看次数

将列表值应用于字典列表

假设我有一个字典列表,如下所示:

final_list = [{'city': 'value', 'population': 'value'}, {'city': 'value', 'population': 'value'}, {'city': 'value', 'population': 'value'}]
Run Code Online (Sandbox Code Playgroud)

我有一个看起来像这样的列表:

input_list = [['London', 'New York', 'San Francisco'], [8908081, 8398748, 883305]]
Run Code Online (Sandbox Code Playgroud)

我想正确的价值观,从地图input_listfinal_list,但我无法弄清楚如何。我想它会是这样的:

n = 0 
while n < len(final_list):
     for category in input_list:
          for section in final_list:
                # then here, somehow say 
                # for the nth item in each of the sections, update the value to nth item in category
                # then increment n
Run Code Online (Sandbox Code Playgroud)

任何帮助将非常感激!提前致谢 :)

python list-comprehension dictionary-comprehension

2
推荐指数
1
解决办法
57
查看次数