Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Join dictionary item, keys [duplicate]

Tags:

python

join

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
like image 893
TechnoBee Avatar asked Jun 02 '14 14:06

TechnoBee


People also ask

Does dictionary accept duplicate keys?

[C#] Dictionary with duplicate keysThe Key value of a Dictionary is unique and doesn't let you add a duplicate key entry. To accomplish the need of duplicates keys, i used a List of type KeyValuePair<> .

How do you join keys in Python?

To join all keys and values, use join() method with list comprehension.


2 Answers

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())
like image 88
m.wasowski Avatar answered Oct 21 '22 18:10

m.wasowski


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.

like image 39
Henry Keiter Avatar answered Oct 21 '22 18:10

Henry Keiter