Appending two or more zeros in a python dictionary - python

I want to add two zeros on a dictionary as values. When i do this the python dictionary returns only a single zero. I don't want to use a list. Why the dictionary behaves like this?
dictionary = {}
#new key and values
dictionary['a'] = {0.0,0.0}
#expected result {'a': {0.0,0.0}}
print(dictionary)
the console returns this as an output.
{'a': {0.0}}

If you don't want to use lists, you can use a tuple, which unlike sets allows duplicates.
In [1]: dictionary = {}
In [2]:
...: dictionary['a'] = (0.0,0.0)
In [3]:
...: print(dictionary)
{'a': (0.0, 0.0)}

Related

What's the difference between '{}' and 'set()' in Python?

When I use
a = {}
and
a = set()
And sometimes I see use like:
a = set([])
Are they the same? What's the difference between them?
I am asking because
a = set(range(5))
b = {0,1,2,3,4}
a == b
>>> True
By default {} means an empty dictionary in python. However, the curly braces are used for both dict and set literals, see the following examples:
empty_set = set()
non_empty_set = {1,2,3}
empty_dict = {}
empty_dict2 = dict()
non_empty_dict = {"a": 1}
avoid using
a = set([]) # instead use a = set()
When you initialise the variable with empty brackets it will be of type dict:
a = {}
print(f"type of a={type(a)}")
Output:
type of a=<class 'dict'>
However, if you initialise it with some values python will detect the type itself.
b = {1, 2, 3}
print(f"type of b={type(b)}")
c = {"some_key": "some_value"}
print(f"type of c={type(c)}")
Output:
type of b=<class 'set'>
type of c=<class 'dict'>
A set and a dictionary are two different data structures. You can read more about them here: Beginner to python: Lists, Tuples, Dictionaries, Sets
The literal {} will be a dictionary with key and value pairs, while set() is a set that contains just pure values. When using more than 0 elements, their literals will be distinguished by whether you include the key value pairs. For example, {1: 'a', 2: 'b'} vs {1, 2}.
They are not the same.
{} creates and empty dictionary (but {1,2,3} creates a set with 3 elements: 1, 2, 3)
set() creates a empty set

Converting dictionary into string

d={'a':'Apple','b':'ball','c':'cat'}
The above dictionary I have and I want my Output like the below-mentioned result
res="a=Apple,b=ball,c=cat"
Is it possible in a pythonic way then please answer it I have tried various method but did not get desired output?
Read your dictionary as key/value pairs (dict.items()) and then just format them in a string you like:
d = {'a': 'Apple', 'b': 'ball', 'c': 'cat'}
res = ",".join("{}={}".format(*i) for i in d.items()) # a=Apple,c=cat,b=ball
The order, tho, cannot be guaranteed for a dict, use collections.OrderedDict() if order is important.
One way is to iterate via dict.items and use multiple str.join calls.
d = {'a':'Apple','b':'ball','c':'cat'}
res = ','.join(['='.join(i) for i in d.items()])
# 'a=Apple,b=ball,c=cat'
If you need items ordered by key, use sorted(d.items()).
def format_dict(d):
vals = list(d.values())
return "={},".join(d.keys()).format(*vals) + "={}".format(vals[-1])
d = {'a': 'Apple', 'b': 'ball', 'c': 'cat'}
format_dict(d) # -> 'a=Apple,b=ball,c=cat'
This joins all the keys into a large string containing replacement fields that we then format passing the dict values as args. There wasn't a trailing replacement field so we concatenate the last value in the dictionary to our large string.
For anyone coming here looking for a way to explicitly extract the dictionary keys and values (e.g. if further formatting is required):
d = {'a':'Apple','b':'ball','c':'cat'}
res = ','.join(f'{k}={v}' for k, v in d.items())
# --> a=Apple, b=ball, c=cat
(uses python 3.6+ f-strings)

Python Dictionary append value error

I'm trying to append a value (list) to a dictionary unsuccessfully. setting the value by 'equal' works, but appending doesn't.
DurationDict = dict()
DurationDict[str(curYear)] = duration // This works
DurationDict[str(curYear)].append(duration) //This does't work.
any ideas?
If you want to append to the value of dictionary, then value should be a type of list.
lets consider following example:
>>> k = {"a":1}
>>> k["b"] = 2
>>> k["c"] = [2]
>>> k["c"].append("new value") # here you can append because value of c is type of list.
>>> print(k)
{'a': 1, 'c': [2, 'new value'], 'b': 2}
>>> k["b"].append("new value") # here you can not append because value of b is type of int
you can append to a list but not to a dict. python dicts are documented here.
if you want to have a list for all your dictionary entries, you can use defaultdict:
collections import defaultdict
DurationDict = defaultdict(list)
DurationDict[str(curYear)].append(duration)
defaultdict works like a normal dict except it returns the result of the 'factory' - in this case list() if the key you are looking up does not exist yet. you can then append to this (empty) list.
You can only append lists. If you have an empty dictionary d,
d = {} # initialize an empty dictionary
d['a'].append(1) # will NOT work
But if you already had an empty list defined,
d = {'a': []} # initialize with an empty list
df['a'].append(1) # will work
>>> d
{'a': [1]}

How can I populate a dictionary with an enumerated list?

I have the following dictionary, where keys are integers and values are floats:
foo = {1:0.001,2:2.097,3:1.093,4:5.246}
This dictionary has keys 1, 2, 3 and 4.
Now, I remove the key '2':
foo = {1:0.001,3:1.093,4:5.246}
I only have the keys 1, 3 and 4 left. But I want these keys to be called 1, 2 and 3.
The function 'enumerate' allows me to get the list [1,2,3]:
some_list = []
for k,v in foo.items():
some_list.append(k)
num_list = list(enumerate(some_list, start=1))
Next, I try to populate the dictionary with these new keys and the old values:
new_foo = {}
for i in num_list:
for value in foo.itervalues():
new_foo[i[0]] = value
However, new_foo now contains the following values:
{1: 5.246, 2: 5.246, 3: 5.246}
So every value was replaced by the last value of 'foo'. I think the problem comes from the design of my for loop, but I don't know how to solve this. Any tips?
Using the list-comprehension-like style:
bar = dict( (k,v) for k,v in enumerate(foo.values(), start=1) )
But, as mentioned in the comments the ordering is going to be arbitrary, since the dict structure in python is unordered. To preserve the original order the following can be used:
bar = dict( ( i,foo[k] ) for i, k in enumerate(sorted(foo), start=1) )
here sorted(foo) returns the list of sorted keys of foo. i is the new enumeration of the sorted keys as well as the new enumeration for the new dict.
Like others have said, it would be best to use a list instead of dict. However, in case you prefer to stick with a dict, you can do
foo = {j+1:foo[k] for j,k in enumerate(sorted(foo))}
Agreeing with the other responses that a list implements the behavior you describe, and so it probably more appropriate, but I will suggest an answer anyway.
The problem with your code is the way you are using the data structures. Simply enumerate the items left in the dictionary:
new_foo = {}
for key, (old_key, value) in enumerate( sorted( foo.items() ) ):
key = key+1 # adjust for 1-based
new_foo[key] = value
A dictionary is the wrong structure here. Use a list; lists map contiguous integers to values, after all.
Either adjust your code to start at 0 rather than 1, or include a padding value at index 0:
foo = [None, 0.001, 2.097, 1.093, 5.246]
Deleting the 2 'key' is then as simple as:
del foo[2]
giving you automatic renumbering of the rest of your 'keys'.
This looks suspiciously like Something You Should Not Do, but I'll assume for a moment that you're simplifying the process for an MCVE rather than actually trying to name your dict keys 1, 2, 3, 4, 5, ....
d = {1:0.001, 2:2.097, 3:1.093, 4:5.246}
del d[2]
# d == {1:0.001, 3:1.093, 4:5.246}
new_d = {idx:val for idx,val in zip(range(1,len(d)+1),
(v for _,v in sorted(d.items())))}
# new_d == {1: 0.001, 2: 1.093, 3: 5.246}
You can convert dict to list, remove specific element, then convert list to dict. Sorry, it is not a one liner.
In [1]: foo = {1:0.001,2:2.097,3:1.093,4:5.246}
In [2]: l=foo.values() #[0.001, 2.097, 1.093, 5.246]
In [3]: l.pop(1) #returns 2.097, not the list
In [4]: dict(enumerate(l,1))
Out[4]: {1: 0.001, 2: 1.093, 3: 5.246}
Try:
foo = {1:0.001,2:2.097,3:1.093,4:5.246}
foo.pop(2)
new_foo = {i: value for i, (_, value) in enumerate(sorted(foo.items()), start=1)}
print new_foo
However, I'd advise you to use a normal list instead, which is designed exactly for fast lookup of gapless, numeric keys:
foo = [0.001, 2.097, 1.093, 5.245]
foo.pop(1) # list indices start at 0
print foo
One liner that filters a sequence, then re-enumerates and constructs a dict.
In [1]: foo = {1:0.001, 2:2.097, 3:1.093, 4:5.246}
In [2]: selected=1
In [3]: { k:v for k,v in enumerate((foo[i] for i in foo if i<>selected), 1) }
Out[3]: {1: 2.097, 2: 1.093, 3: 5.246}
I have a more compact method.
I think it's more readable and easy to understand. You can refer as below:
foo = {1:0.001,2:2.097,3:1.093,4:5.246}
del foo[2]
foo.update({k:foo[4] for k in foo.iterkeys()})
print foo
So you can get answer you want.
{1: 5.246, 3: 5.246, 4: 5.246}

How to implement associative array (not dictionary) in Python?

I trying to print out a dictionary in Python:
Dictionary = {"Forename":"Paul","Surname":"Dinh"}
for Key,Value in Dictionary.iteritems():
print Key,"=",Value
Although the item "Forename" is listed first, but dictionaries in Python seem to be sorted by values, so the result is like this:
Surname = Dinh
Forename = Paul
How to print out these with the same order in code or the order when items are appended in (not sorted by values nor by keys)?
You can use a list of tuples (or list of lists). Like this:
Arr= [("Forename","Paul"),("Surname","Dinh")]
for Key,Value in Arr:
print Key,"=",Value
Forename = Paul
Surname = Dinh
you can make a dictionary out of this with:
Dictionary=dict(Arr)
And the correctly sorted keys like this:
keys = [k for k,v in Arr]
Then do this:
for k in keys: print k,Dictionary[k]
but I agree with the comments on your question: Would it not be easy to sort the keys in the required order when looping instead?
EDIT: (thank you Rik Poggi), OrderedDict does this for you:
od=collections.OrderedDict(Arr)
for k in od: print k,od[k]
First of all dictionaries are not sorted at all nor by key, nor by value.
And basing on your description. You actualy need collections.OrderedDict module
from collections import OrderedDict
my_dict = OrderedDict([("Forename", "Paul"), ("Surname", "Dinh")])
for key, value in my_dict.iteritems():
print '%s = %s' % (key, value)
Note that you need to instantiate OrderedDict from list of tuples not from another dict as dict instance will shuffle the order of items before OrderedDict will be instantiated.
You can use collections.OrderedDict. It's available in python2.7 and python3.2+.
This may meet your need better:
Dictionary = {"Forename":"Paul","Surname":"Dinh"}
KeyList = ["Forename", "Surname"]
for Key in KeyList:
print Key,"=",Dictionary[Key]
'but dictionaries in Python are sorted by values' maybe I'm mistaken here but what game you that ideea? Dictionaries are not sorted by anything.
You would have two solutions, either keep a list of keys additional to the dictionary, or use a different data structure like an array or arrays.
I wonder if it is an ordered dict that you want:
>>> k = "one two three four five".strip().split()
>>> v = "a b c d e".strip().split()
>>> k
['one', 'two', 'three', 'four', 'five']
>>> v
['a', 'b', 'c', 'd', 'e']
>>> dx = dict(zip(k, v))
>>> dx
{'four': 'd', 'three': 'c', 'five': 'e', 'two': 'b', 'one': 'a'}
>>> for itm in dx:
print(itm)
four
three
five
two
one
>>> # instantiate this data structure from OrderedDict class in the Collections module
>>> from Collections import OrderedDict
>>> dx = OrderedDict(zip(k, v))
>>> for itm in dx:
print(itm)
one
two
three
four
five
A dictionary created using the OrderdDict preserves the original insertion order.
Put another way, such a dictionary iterates over the key/value pairs according to the order in which they were inserted.
So for instance, when you delete a key and then add the same key again, the iteration order is changes:
>>> del dx['two']
>>> for itm in dx:
print(itm)
one
three
four
five
>>> dx['two'] = 'b'
>>> for itm in dx:
print(itm)
one
three
four
five
two
As of Python 3.7, regular dicts are guaranteed to be ordered, so you can just do
Dictionary = {"Forename":"Paul","Surname":"Dinh"}
for Key,Value in Dictionary.items():
print(Key,"=",Value)

Categories