Hi,

Just to complete: dict.fromkeys is an optimized routine to create a dictionary with given keys and a default value. By default, the value is None

sage: dict.fromkeys([0,1,2,3,4,5])
{0: None, 1: None, 2: None, 3: None, 4: None, 5: None}

This is faster than anything else to create a dictionary.

Vincent

On 20/05/15 08:14, Huayi Wei wrote:
Hi, Dan, Thanks very much! It works very well. -- Huayi

On 2015年05月20日 09:39, Dan Drake wrote:
On Wed, 20 May 2015 at 06:27AM +0800, Huayi Wei wrote:
Hi, everyone,

I want to create a sparse matrix, so I need to create a dict first.
I try to use `dict.fromkeys()` to do it, which like following:

```
sage: keys = [(0,1),(1,2)] # the length of keys maybe very long
sage: values = [0,1] # values have the same length as keys
sage: d = dict.fromkeys(keys,values)
sage: d
{(0, 1): [0, 1], (1, 2): [0, 1]}
```
But the result is not what I want, and I want to get this:

```
{(0,1):0,(1,2):1}
```

Does there exist other way to do this? Hope to get your help, thanks
very much.
Try just "dict()":

dict(zip(keys, values))
{(0, 1): 0, (1, 2): 1}

Here's how zip() works, if you don't already know:
https://docs.python.org/3.5/library/functions.html#zip


Dan





--
You received this message because you are subscribed to the Google Groups 
"sage-support" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to sage-support+unsubscr...@googlegroups.com.
To post to this group, send email to sage-support@googlegroups.com.
Visit this group at http://groups.google.com/group/sage-support.
For more options, visit https://groups.google.com/d/optout.

Reply via email to