用字典推导式以字符串以及其长度建字典
时间: 2023-06-05 17:05:18 浏览: 36
很高兴回答你的问题。以下是可以回答的Python代码:
```
string = "Hello World"
d = {s:len(s) for s in string.split()}
print(d)
```
输出结果为:
```
{'Hello': 5, 'World': 5}
```
如果您有任何其他问题,请随时问我。
相关问题
用字典推导式以字符串以及其长度建字典 country = ['China','Japan','Korea','India','Thailand','Indonesia'] 输出 {'China': 5, 'Japan': 5, 'Korea': 5, 'India': 5, 'Thailand': 8, 'Indonesia': 9}
好的,这是一个Python编程问题,我可以回答。以下是代码实现:
country = ['China', 'Japan', 'Korea', 'India', 'Thailand', 'Indonesia']
country_dict = {c: len(c) for c in country}
print(country_dict)
输出结果为:
{'China': 5, 'Japan': 5, 'Korea': 5, 'India': 5, 'Thailand': 8, 'Indonesia': 9}
List1=[‘Google’,’BLCU’,’Taobao’],使用字典推导式和内置函数两种方法将列表List1中各元素字符串值为键,各元素字符串长度为值,组成键值对:dict=[‘Google’:6,’BLCU’:4,’Taobao’:6]
使用字典推导式:
```
List1 = ['Google', 'BLCU', 'Taobao']
my_dict = {key: len(key) for key in List1}
print(my_dict)
```
使用内置函数`map()`和`zip()`:
```
List1 = ['Google', 'BLCU', 'Taobao']
my_dict = dict(zip(List1, map(len, List1)))
print(my_dict)
```