Join dictionary item, keys [duplicate] - python

This question already has answers here:
Iterating over dictionaries using 'for' loops
(15 answers)
Closed 8 years ago.
Please see below code snippet for join method (used Python 2.7.2):
iDict={'1_key':'abcd','2_key':'ABCD','3_key':'bcde','4_key':'BCDE'}
'--'.join(iDict)
Result shown as
'2_key--1_key--4_key--3_key'
Please comment why only keys are joined? Also the sequence is not in order.
Note - below are the individual methods.
'--'.join(iDict.values()) ==> 'ABCD--abcd--BCDE--bcde' ==> the sequence is not in order
'--'.join(iDict.keys()) ==> '2_key--1_key--4_key--3_key' ==> the sequence is not in orde

If you see the docs, you learn that iterating over dict returns keys.
You need to iterate over dict.items(), that it over tuples (key, value):
'--'.join(iDict.items())
If you need to have key AND value joined in one string, you need to explicitly tell Python how to do this:
'--'.join('{} : {}'.format(key, value) for key, value in iDict.items())

Python dictionaries are unordered (or rather, their order is arbitrary), and when you iterate on them, only the keys are returned:
>>> d = {'0':0, '1':1, '2':2, '3':3, '4':4}
>>> print(d)
{'4': 4, '1': 1, '0': 0, '3': 3, '2': 2}
If you need both keys and values, use iDict.items().
If you need ordering, use collections.OrderedDict.

Iteration over a dictionary only ever yields keys:
>>> list(iDict)
['2_key', '1_key', '4_key', '3_key']
See the dict() documentation:
iter(d)
Return an iterator over the keys of the dictionary. This is a shortcut for iterkeys().
Both list() and str.join() will call iter() on their arguments to iterate over the elements.
Dictionaries are unordered containers; their order stems from the underlying data structure and depends on the insertion and deletion history of the keys.
This is documented under dict.items():
CPython implementation detail: Keys and values are listed in an arbitrary order which is non-random, varies across Python implementations, and depends on the dictionary’s history of insertions and deletions.
Also see Why is the order in dictionaries and sets arbitrary?

Related

What determines if a dictionarie's items are ordered or not? [duplicate]

This question already has answers here:
How to keep keys/values in same order as declared?
(13 answers)
Closed 3 years ago.
I've started a python crash course and this is an excerpt of it, pertaining to dictionaries
myDict = {'One':1.35, 2.5:'Two Point Five', 3:'+', 7.9:2}
# print the entire dictionary
print(myDict)
You’ll get {2.5: 'Two Point Five', 3: '+', 'One': 1.35, 7.9: 2}
Note that items in a dictionary are not stored in the same order as the way you declare them.
I've replicated that, and in my case the items are printed as I declared them. Why am I getting a different result?
My output:
myDict = {'One':1.35, 2.5:'Two Point Five', 3:'+', 7.9:2}
#print the entire dictionary
print(myDict)
Output: {'One': 1.35, 2.5: 'Two Point Five', 3: '+', 7.9: 2}
Dictionaries differ from lists as they can't be indexed like them and furthermore, they are "unsorted". However, in newer versions of python, you get the same order as you used to set up the dictionary. If the course you watched used an older version of python, it should explain why the result was random.
Python dictionaries are ordered by design since python 3.7 (sorting if it makes sense). If you use python 3.6 or lower, you can order your dictionary by storing its keys in a list, sort the list and loop through the list.
dictionary always follows a key(always string format), value(any format) pair it doesn't know about order and unorders you always fetch data from the dictionary using the key name.
You can order your dictionary, but it based on the value of your dictionary, not key and your key order will be changed according to your new order values.

What is the difference between using brackets "[]" and parentheses "()" for "fields" in django-rest-framework [duplicate]

What's the difference between () vs [] vs {} in Python?
They're collections? How can I tell when to use which?
() - tuple
A tuple is a sequence of items that can't be changed (immutable).
[] - list
A list is a sequence of items that can be changed (mutable).
{} - dictionary or set
A dictionary is a list of key-value pairs, with unique keys (mutable). From Python 2.7/3.1, {} can also represent a set of unique values (mutable).
() is a tuple: An immutable collection of values, usually (but not necessarily) of different types.
[] is a list: A mutable collection of values, usually (but not necessarily) of the same type.
{} is a dict: Use a dictionary for key value pairs.
For the difference between lists and tuples see here. See also:
Python Tuples are Not Just Constant Lists
() - tuple
[] - list
{} - dictionary
All Python tutorials should cover this. Here is a good place to start.
In addition to the tuple, list and dict given by the other answers, {} also denotes a set literal in python 2.7 and python 3.1. (This makes sense because set elements act like the keys of a dict).
To complete the other answers about {}:
If you see a = {"key1": 1, "key2": 2, "key3": 3} (keys and values), then it's a dict.
If you see a = {1, 2, 3} (values only), then it's a set.
If you see a = {} (empty), then it's a dict. An empty set is created with a = set().
Quoting the official doc:
5.4. Sets
Python also includes a data type for sets. A set is an unordered collection with no duplicate elements. Basic uses include membership testing and eliminating duplicate entries. Set objects also support mathematical operations like union, intersection, difference, and symmetric difference.
Curly braces or the set() function can be used to create sets. Note: to create an empty set you have to use set(), not {}; the latter creates an empty dictionary, a data structure that we discuss in the next section.

dict_key and dict_value to list performances [duplicate]

This question already has answers here:
Accessing dict_keys element by index in Python3
(7 answers)
Closed 2 years ago.
I have this sentence:
def Ciudad(prob):
numero = random.random()
ciudad = prob.keys()[0]
for i in prob.keys():
if(numero > prob[i]):
if(prob[i] > prob[ciudad]):
ciudad = i
else:
if(prob[i] > prob[ciudad]):
ciudad = i
return ciudad
But when I call it this error pops:
TypeError: 'dict_keys' object does not support indexing
is it a version problem? I'm using Python 3.3.2
dict.keys() is a dictionary view. Just use list() directly on the dictionary instead if you need a list of keys, item 0 will be the first key in the (arbitrary) dictionary order:
list(prob)[0]
or better still just use:
next(iter(dict))
Either method works in both Python 2 and 3 and the next() option is certainly more efficient for Python 2 than using dict.keys(). Note however that dictionaries have no set order and you will not know what key will be listed first.
It looks as if you are trying to find the maximum key instead, use max() with dict.get:
def Ciudad(prob):
return max(prob, key=prob.get)
The function result is certainly going to be the same for any given prob dictionary, as your code doesn't differ in codepaths between the random number comparison branches of the if statement.
In Python 3.x, dict.keys() does not return a list, it returns an iterable (specifically, a dictionary view). It is worth noting that dict itself is also an iterable of the keys.
If you want to obtain the first key, use next(iter(dict)) instead. (Note that before Python 3.6 dictionaries were unordered, so the 'first' element was an arbitrary one. Since 3.6 it will be based on insertion order. If you need that behaviour in older versions or with cross-version compatibility, you can use collections.OrderedDict).
This works quite simply: we take the iterable from the dictionary view with iter(), then use next() to advance it by one and get the first key.
If you need to iterate over the keys—then there is definitely no need to construct a list:
for key in dict:
...
These are all advantageous when compared to using list() as it means a list isn't constructed - making it faster and more memory efficient (hence why the default behaviour of keys() was changed in 3.x). Even in Python 2.x you would be better off doing next(iter(dict.iterkeys()).
Note all these things apply to dict.values() and dict.items() as well.
I've had success turning the iterables taken from a dictionary into a list.
So, for dic.keys(), dic.values(), and dic.items(), in Python3.6, you can:
dic = {'a':3, 'b':2, 'c':3}
print(dic)
dictkeys = dic.keys() # or values/items
print(dictkeys)
keylist = []
keylist.extend(iter(dictkeys)) # my big revelation
print('keylist', keylist)

Python: get key of index in dictionary [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Inverse dictionary lookup - Python
reverse mapping of dictionary with Python
How do i get key of index in dictionary?
For example like:
i = {'a': 0, 'b': 1, 'c': 2}
so if i want to get key of i[0], it will return 'a'
You could do something like this:
i={'foo':'bar', 'baz':'huh?'}
keys=i.keys() #in python 3, you'll need `list(i.keys())`
values=i.values()
print keys[values.index("bar")] #'foo'
However, any time you change your dictionary, you'll need to update your keys,values because dictionaries are not ordered in versions of Python prior to 3.7. In these versions, any time you insert a new key/value pair, the order you thought you had goes away and is replaced by a new (more or less random) order. Therefore, asking for the index in a dictionary doesn't make sense.
As of Python 3.6, for the CPython implementation of Python, dictionaries remember the order of items inserted. As of Python 3.7+ dictionaries are ordered by order of insertion.
Also note that what you're asking is probably not what you actually want. There is no guarantee that the inverse mapping in a dictionary is unique. In other words, you could have the following dictionary:
d={'i':1, 'j':1}
In that case, it is impossible to know whether you want i or j and in fact no answer here will be able to tell you which ('i' or 'j') will be picked (again, because dictionaries are unordered). What do you want to happen in that situation? You could get a list of acceptable keys ... but I'm guessing your fundamental understanding of dictionaries isn't quite right.
Python dictionaries have a key and a value, what you are asking for is what key(s) point to a given value.
You can only do this in a loop:
[k for (k, v) in i.iteritems() if v == 0]
Note that there can be more than one key per value in a dict; {'a': 0, 'b': 0} is perfectly legal.
If you want ordering you either need to use a list or a OrderedDict instance instead:
items = ['a', 'b', 'c']
items.index('a') # gives 0
items[0] # gives 'a'
By definition dictionaries are unordered, and therefore cannot be indexed. For that kind of functionality use an ordered dictionary. Python Ordered Dictionary

Why dictionary values aren't in the inserted order?

When i declare a list 1,2,3,4 and i do something with it , even just print i get back the same sequence 1,2,3,4.
But when i do anything with dictionaries , they always change number sequence , like it is being sorted in a twisted way i can't understand .
test1 = [4,1,2,3,6,5]
print test1
test2 = {"c":3,"a":1,"b":2,"d":4}
print test2
[4, 1, 2, 3, 6, 5]
{'a': 1, 'c': 3, 'b': 2, 'd': 4}
How in the world did 'a' become the first element and 'c' , even if it alphabetically sorted the dictionary it should have been 1,2,3,4 or a,b,c,d not 1,3,2,4 . wT?F #!$!#$##!
So how do i print , get values from dictionary without changing the positions of the elements .?
Dictionaries in Python are unordered by definition. Use OrderedDict if you need the order in which values were inserted (it's available in Python 2.7 and 3.x).
dictionary sort order is undefined! Do not rely on it for anything. Look for a sorted dictionary if you really want a sorted dictionary, but usually you don't need one.
Examples:
python 2.7, it's built in to the collections module
Django has a SortedDict shipped with it
2.4-2.7 you can use the ordereddict module, you can pip install or easy_install it
Before you get so angry and frustrated, perhaps you should read about what a dictionary actually is and how it works:
http://docs.python.org/library/stdtypes.html#mapping-types-dict
Python dicts use a hash table as the underlying storage mechanism. That means that a hash key is generated from the key that you provide. There are no guarantees about ordering with these hash keys. The entries in a dictionary are fetched in sequential order of their location in the underlying hash table when you request values(), keys(), or items().
The advantage of using a hash table is that it is extremely fast. Unlike the map class from c++ which uses a red-black tree storage mechanism ( which is sorted by the raw keys ), a hash table doesn't constantly need to be restructured to keep it efficient. For more on hash tables, see:
http://en.wikipedia.org/wiki/Hash_table
Like the other posters have said, look up OrderedDict if you need to have a key-sorted dictionary.
Good Luck!
Clearly you know about lists. You can ask for the element at the ith index of a list. This is because lists are ordered.
>>> [1,2,3,4] == [1,4,3,2]
False
In this context, you can think of dictionaries, but where the index is the key. Therefore, two dictionaries are equal if the corresponding values of all keys in both dictionaries are the same (if one dictionary has keys that the other doesn't, then the two are not equal). Thus:
>>> {1:'a', 2:'b'} == {2:'b', 1:'a'}
True
Further Trivia
A dictionary does something called hashing on the keys of the dictionary so that when you ask for the value at a particular key (index), it can retrieve this value faster.
Hope this helps
Dictionaries are unsorted. This is well-documented. Do not rely on the ordering of dictionaries.
If you want to see the entries in order. something like:
test2 = {"c":3,"a":1,"b":2,"d":4}
ks = test2.keys()
ks.sort()
for key in ks:
print key + ':' + str(test2[key])
(cut,paste, season to taste)

Categories

Resources