标签: dictionary-comprehension

来自文件的 Python 字典理解

我试图让我的 python 代码中的所有内容都具有理解性。我必须将 .txt 文件数据转换为字典。它看起来像这样:

A   .-
B   -...
C   -.-.
...
Run Code Online (Sandbox Code Playgroud)

是的,这是摩尔斯电码。

我的代码如下所示:

def morse_file_to_dict(filename):
    d = {}
    for line in open(filename):
        ch, sign = line.strip().split('\t')
        d[ch] = sign
    return d
Run Code Online (Sandbox Code Playgroud)

它返回一个正常的字典,如下所示:

{'A': '.-', 'B': '-...', 'C': '-.-.', ... }
Run Code Online (Sandbox Code Playgroud)

我的问题是,我可以在一行中完成这个吗?有领悟力吗?

感谢您的时间和答复!

python for-comprehension dictionary-comprehension

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

是否可以编写一个以特定格式返回多个值的函数?

我正在编写一个返回两个值的函数,这两个值将形成字典的键值对。该函数将用于创建具有字典理解的字典。但是,使用字典理解,需要以“键:值”的格式提供值对。为了实现这一点,我必须调用该函数两次。一次用于键,一次用于值。例如,

sample_list = [['John', '24', 'M', 'English'], 
               ['Jeanne', '21', 'F', 'French'],
               ['Yuhanna', '22', 'M', 'Arabic']]

def key_value_creator(sample_list):
   key = sample_list[0]
   value = {'age': sample_list[1],
            'gender': sample_list[2], 
            'lang': sample_list[3]}

   return key, value

dictionary = {key_value_creator(item)[0]: \
              key_value_creator(item)[1] for item in sample_list}
Run Code Online (Sandbox Code Playgroud)

正如您所看到的,该函数被调用两次以生成可以在一次运行中生成的值。有没有办法以可理解的格式返回值?如果可能的话,该函数只需调用一次,如下所示:

dictionary = {key_value_creator(item) for item in sample_list}
Run Code Online (Sandbox Code Playgroud)

据我所知,返回多个值的其他方法是以字典或列表的形式返回它们,

return {'key': key, 'value': value}
Run Code Online (Sandbox Code Playgroud)
return [key, value]
Run Code Online (Sandbox Code Playgroud)

但无论哪种方式,要访问它们,我们都必须调用该函数两次。

dictionary = {key_value_creator(item)['key']: \
              key_value_creator(item)['value'] for item in sample_list}
Run Code Online (Sandbox Code Playgroud)
dictionary = {key_value_creator(item)[0]: \
              key_value_creator(item)[1] for item in sample_list}
Run Code Online (Sandbox Code Playgroud)

有没有办法格式化这些值,以便我们可以将它们以字典理解语句所需的格式发送到它?

编辑:预期输出:

{ 'John': …
Run Code Online (Sandbox Code Playgroud)

python dictionary return dictionary-comprehension

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

当我从同一个函数中获取键和值时,使用字典理解构建一个 dict

假设我有一个复杂的函数get_stuff,它接受一个 int 并返回一个元组,第一个元素的类型是 str。下面的示例具有相同的行为,但假设实际函数更复杂并且不能轻易地一分为二:

def get_stuff(x):
    return str(5*x),float(3*x)
Run Code Online (Sandbox Code Playgroud)

我想要的是构建一个 dict,其 (key,value) 对是在特定整数集上调用时 get_stuff 的结果。一种方法是:

def get_the_dict(set_of_integers):
    result = {}
    for i in set_of_integers:
        k,v = get_stuff(i)
        result[k] = v
    return result
Run Code Online (Sandbox Code Playgroud)

我宁愿为此使用 dict comprehension,但我不知道是否可以在理解中拆分该对以分别捕获键和值。

def get_the_dict_with_comprehension(set_of_integers):
    return {get_stuff(i) for i in set_of_integers} #of course this doesn't work
Run Code Online (Sandbox Code Playgroud)

我怎样才能做到这一点?

python dictionary-comprehension

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

带有附加键的字典理解

我的字典理解如下所示:

bar = {
    n: n**2
    for n in range(1, 10)
}
Run Code Online (Sandbox Code Playgroud)

有没有办法在同一表达式中向字典添加附加键?我在想这样的事情:

bar = {
    'foo': 'bar',
    n: n**2
    for n in range(1, 10)
}
Run Code Online (Sandbox Code Playgroud)

但这不起作用。我怎样才能实现这个目标?现在,我随后手动添加附加条目,但如果我可以在相同的表达式中执行此操作,那就太好了。

我知道我的示例中的用例不是很清楚,但在我的实际代码中它会让事情变得容易得多。

python python-3.x dictionary-comprehension

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

可以压缩成字典理解吗?

index = [x for x in range(0,81)]
membership_columns = {
    'column_0': index[0:81:9]
    'column_1': index[1:81:9]
    'column_2': index[2:81:9]
    'column_3': index[3:81:9]
    'column_4': index[4:81:9]
    'column_5': index[5:81:9]
    'column_6': index[6:81:9]
    'column_7': index[7:81:9]
    'column_8': index[8:81:9]
    }
Run Code Online (Sandbox Code Playgroud)

有可能将其压缩成词典理解吗?另外,第1行的列表理解是否必要?我不确定如何将每个键单独转换为列表理解.

python list-comprehension dictionary-comprehension

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

Python字典理解和循环之间的区别

我正在使用Python 3.4,我正在测试字典理解.

假设我有以下代码:

listofdict = [{"id":1, "title": "asc", "section": "123"},{"id":2, "title": "ewr", "section": "456"}]
titles1 = []
titles2 = []
titles1.append({r["section"]: r["title"] for r in listofdict})
print("titles1 = " + str(titles1))

for r in listofdict:
  section = r["section"]
  title = r["title"]
  titles2.append({section: title})

print("titles2 = " + str(titles2))
Run Code Online (Sandbox Code Playgroud)

我认为这两种方法应该给我相同的结果,但我得到以下内容:

titles1 = [{'456': 'ewr', '123': 'asc'}]
titles2 = [{'123': 'asc'}, {'456': 'ewr'}]
Run Code Online (Sandbox Code Playgroud)

titles2是我真正想要的,但我想使用字典理解来做到这一点.

编写字典理解的正确方法是什么?

python dictionary dictionary-comprehension

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

python dict理解在本地工作但不在服务器上 - 版本问题

我对以下内容感到非常困惑.我想创建一个将id名称映射到列表项的字典:

itemsKeyedById = {i["id"]: i for i in myList}
Run Code Online (Sandbox Code Playgroud)

它在我的电脑上执行时正常工作.myList是由一系列命令创建的列表,例如:

myList.append({'name': 'entry_name_string', 'id': 'some_id'})
Run Code Online (Sandbox Code Playgroud)

当我将其上传到服务器时,脚本只是"挂起"在这一行.

我在本地的python版本是Python 2.7.10,在服务器上我有2.6.6.也许这是版本问题,但我对python很新,从未在2.6.6中编程.任何建议将不胜感激.

谢谢大家 :-)

python dictionary-comprehension

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

python词典理解方法中的单行if else

我刚试过这样的列表理解

[i if i==0 else i+100for i in range(0,3)]
Run Code Online (Sandbox Code Playgroud)

它工作,但当我尝试类似的字典理解时,它会抛出一个错误:

d={3:3}
{d[i]:0 if i==3 else d[i]:True for i in range(0,4) }
Run Code Online (Sandbox Code Playgroud)

可能是什么原因?我怎样才能使用dict理解if else

这会产生错误:

    {d[i]:0 if i==3 else d[i]:True for i in range(0,4) }
                             ^
SyntaxError: invalid syntax
Run Code Online (Sandbox Code Playgroud)

注意:我在这里使用的示例只是一个随机的,而不是我的实际代码.我可以用替代解决方案来做到这一点,但我现在只是在研究dict理解.

python list-comprehension dictionary-comprehension

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

使用嵌套的元组列表创建Python defaultdict

场景是我有一个2-D列表.内部列表的每个项目都是元组(键,值对).密钥可能会在列表中重复出现.我想动态创建一个默认字典,最后,字典存储密钥,以及二维列表中该密钥的所有值的累积和.

把代码放到:

listOfItems = [[('a', 1), ('b', 3)], [('a', 6)], [('c', 0), ('d', 5), ('b', 2)]]
finalDict = defaultdict(int)
for eachItem in listOfItems:
    for key, val in eachItem:
        finalDict[key] += val
print(finalDict)
Run Code Online (Sandbox Code Playgroud)

这给了我想要的东西:defaultdict(<class 'int'>, {'a': 7, 'b': 5, 'c': 0, 'd': 5})但我正在寻找一种更加"Pythonic"的方式来使用理解.所以我尝试了以下内容:

finalDict = defaultdict(int)
finalDict = {key : finalDict[key]+val for eachItem in listOfItems for key, val in eachItem}
print(finalDict)
Run Code Online (Sandbox Code Playgroud)

但输出结果是:{'a': 6, 'b': 2, 'c': 0, 'd': 5}我做错了什么?或者是在使用理解时,不会动态创建和修改词典?

python nested-lists python-3.x defaultdict dictionary-comprehension

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

Counting Lists and Adding to a new Dictionary (Python)

I'm working with dictionaries and was wondering how I could output a dictionary where its key is the word that occurs in a given dictionary and its value is the number of times it occurs within that dictionary.

So say for example,

A = {'#1': ['Yellow', 'Blue', 'Red'], '#2': ['White', 'Purple', 'Purple', 'Red']}
B - []
for key in A:
    B.append(A[key])

>>> B
>>> [['Yellow', 'Blue', 'Red'], ['White', 'Purple', 'Purple', 'Red']]
Run Code Online (Sandbox Code Playgroud)

After returning the respective values of the keys, I …

python dictionary dictionary-comprehension

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