python-3.5

Dict merge in a dict comprehension

柔情痞子 提交于 2019-12-03 15:27:52
问题 In python 3.5, we can merge dicts by using double-splat unpacking >>> d1 = {1: 'one', 2: 'two'} >>> d2 = {3: 'three'} >>> {**d1, **d2} {1: 'one', 2: 'two', 3: 'three'} Cool. It doesn't seem to generalise to dynamic use cases, though: >>> ds = [d1, d2] >>> {**d for d in ds} SyntaxError: dict unpacking cannot be used in dict comprehension Instead we have to do reduce(lambda x,y: {**x, **y}, ds, {}) , which seems a lot uglier. Why the "one obvious way to do it" is not allowed by the parser, when

In-place custom object unpacking different behavior with __getitem__ python 3.5 vs python 3.6

a 夏天 提交于 2019-12-03 13:23:55
a follow-up question on this question : i ran the code below on python 3.5 and python 3.6 - with very different results: class Container: KEYS = ('a', 'b', 'c') def __init__(self, a=None, b=None, c=None): self.a = a self.b = b self.c = c def keys(self): return Container.KEYS def __getitem__(self, key): if key not in Container.KEYS: raise KeyError(key) return getattr(self, key) def __str__(self): # python 3.6 # return f'{self.__class__.__name__}(a={self.a}, b={self.b}, c={self.c})' # python 3.5 return ('{self.__class__.__name__}(a={self.a}, b={self.b}, ' 'c={self.c})').format(self=self) data0 =

Failing to import itertools in Python 3.5.2

て烟熏妆下的殇ゞ 提交于 2019-12-03 12:07:51
I am new to Python. I am trying to import izip_longest from itertools. But I am not able to find the import "itertools" in the preferences in Python interpreter. I am using Python 3.5.2. It gives me the below error- from itertools import izip_longest ImportError: cannot import name 'izip_longest' Please let me know what is the right course of action. I have tried Python 2.7 too and ended up with same problem. Do I need to use lower version Python. Martijn Pieters izip_longest was renamed to zip_longest in Python 3 (note, no i at the start), import that instead: from itertools import zip

typing module - String Literal Type [duplicate]

≯℡__Kan透↙ 提交于 2019-12-03 11:29:03
This question already has answers here : Type hint for a function that returns only a specific set of values (3 answers) I'm using the new Python 3.5 module typing and it has been joyous. I was wondering how one might specify a type based on an exact string literal. For example, a function is guaranteed to return one of the four strings - "North", "West", "East", "South - how can we express that as a specific type variable, instead of just str . I looked through the documentation, finding the Union type and the TypeVar function, but was unable to find an answer. An example function expressing

Python3 write gzip file - memoryview: a bytes-like object is required, not 'str'

落爺英雄遲暮 提交于 2019-12-03 11:13:20
I want to write a file. Based on the name of the file this may or may not be compressed with the gzip module. Here is my code: import gzip filename = 'output.gz' opener = gzip.open if filename.endswith('.gz') else open with opener(filename, 'wb') as fd: print('blah blah blah'.encode(), file=fd) I'm opening the writable file in binary mode and encoding my string to be written. However I get the following error: File "/usr/lib/python3.5/gzip.py", line 258, in write data = memoryview(data) TypeError: memoryview: a bytes-like object is required, not 'str' Why is my object not a bytes? I get the

ImportError: No module named 'urllib2' Python 3 [duplicate]

♀尐吖头ヾ 提交于 2019-12-03 09:57:37
This question already has answers here : Import error: No module name urllib2 (8 answers) The below code is working fine on Python 2 but on Python 3 I get the error: "ImportError: No module named 'urllib2'" import urllib2 peticion = 'I'm XML' url_test = 'I'm URL' req = urllib2.Request(url=url_test, data=peticion, headers={'Content-Type': 'application/xml'}) respuesta = urllib2.urlopen(req) print(respuesta) print(respuesta.read()) respuesta.open() Please suggest me the reason of error. Thank you. Prashant Puri check StackOverflow Link import urllib.request url = "http://www.google.com/" request

Did something about `namedtuple` change in 3.5.1?

允我心安 提交于 2019-12-03 09:23:05
On Python 3.5.0: >>> from collections import namedtuple >>> cluster = namedtuple('Cluster', ['a', 'b']) >>> c = cluster(a=4, b=9) >>> c Cluster(a=4, b=9) >>> vars(c) OrderedDict([('a', 4), ('b', 9)]) On Python 3.5.1: >>> from collections import namedtuple >>> cluster = namedtuple('Cluster', ['a', 'b']) >>> c = cluster(a=4, b=9) >>> c Cluster(a=4, b=9) >>> vars(c) Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: vars() argument must have __dict__ attribute Seems like something about namedtuple changed (or maybe it was something about vars() ?). Was this

How make Drag and Drop interface? [duplicate]

随声附和 提交于 2019-12-03 09:16:11
This question already has answers here : Drag and Drop widgets tkinter (2 answers) Currently, I am working with Python 3.5 GUI development using tkinter module. I want to be able to drag an image from one place to another within the application. Does tkinter support drag and drop within an application, and if so, how do you do it? The question Drag and Drop in Tkinter? is asking about dragging and dropping between applications, which is not what I'm asking here. from tkinter import * root = Tk() root.geometry("640x480") canvas = Canvas(root, height=480, width=640, bg="white") frame = Frame

Dict merge in a dict comprehension

自闭症网瘾萝莉.ら 提交于 2019-12-03 05:55:41
In python 3.5, we can merge dicts by using double-splat unpacking >>> d1 = {1: 'one', 2: 'two'} >>> d2 = {3: 'three'} >>> {**d1, **d2} {1: 'one', 2: 'two', 3: 'three'} Cool. It doesn't seem to generalise to dynamic use cases, though: >>> ds = [d1, d2] >>> {**d for d in ds} SyntaxError: dict unpacking cannot be used in dict comprehension Instead we have to do reduce(lambda x,y: {**x, **y}, ds, {}) , which seems a lot uglier. Why the "one obvious way to do it" is not allowed by the parser, when there doesn't seem to be any ambiguity in that expression? It's not exactly an answer to your question

Python 3.5 iterate through a list of dictionaries

谁说我不能喝 提交于 2019-12-03 04:24:48
问题 My code is index = 0 for key in dataList[index]: print(dataList[index][key]) Seems to work fine for printing the values of dictionary keys for index = 0. But for the life of me I can't figure out how to put this for loop inside a for loop that iterates through the unknown number of dictionaries in dataList 回答1: You could just iterate over the indices of the range of the len of your list : dataList = [{'a': 1}, {'b': 3}, {'c': 5}] for index in range(len(dataList)): for key in dataList[index]: